5

I am new to angular 2, I tried [(ngModel)] as shown below.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input [(ngModel)]="model.name" name="name"> <h1>{{model.name}}</h1>`
})
export class AppComponent  { 
constructor() {
}
model = {name: "some value"};
}

The above code produces output like shown below on initial load of web page in browser..

model.name gets bind to view on page load

The second one is..

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input [(ngModel)]="model.name" name="name"> <h1>{{model.name}}</h1>`
})
export class AppComponent  { 
constructor() {
}
model = {};
model.name = "some value";
}

This one produces following output..

If i define model = {} and model.name = "some value it does not appearing in view on page load"

Please Kindly Explain Difference Between Two Code Samples and Why It's Not Working in Second Sample..

Thanks In Advance.

eko
  • 39,722
  • 10
  • 72
  • 98
Yuvaraj V
  • 1,020
  • 2
  • 16
  • 28

1 Answers1

3

Because you can't do assignments there. You can move the assignment into the constructor or to any other life-cycle method:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input [(ngModel)]="model.name" name="name"> <h1>{{model.name}}</h1>`
})
export class AppComponent  { 
constructor() {
   this.model.name = "some value";
}
model = {};

}

Also if you look at your transpiled js file you will see something like:

function AppComponent() {
      this.model = {};
      this.name = "some value";
}
eko
  • 39,722
  • 10
  • 72
  • 98
  • Why I can't do assignments there? and If I can't do assignments there then how we can able to assign {} to model ? Please Clarify Me.. and Thanks For your answer – Yuvaraj V Nov 25 '16 at 11:28
  • 2
    https://plnkr.co/edit/slL7l8yvOe4aO5dm3Q3X?p=preview You can't have arbitrary code at class top-level. Only property and method declarations are allowed. Code has to go into the constructor or into methods. – Günter Zöchbauer Nov 25 '16 at 11:31
  • @shivaraj you didn't assign {} to the model, you've created an object there. And then you've tried to change the property of that object you've created. – eko Nov 25 '16 at 11:33
  • Thanks, But The Code Mentioned In Answer Is Legal One..? Why I am Asking This Because If I compile it with npm run tsc it failed with app/app.component.ts(9,12): error TS2339: Property 'name' does not exist on type '{}'. but got successfully get compiled while running npm run tsc:w ? why ? – Yuvaraj V Nov 25 '16 at 11:47
  • @shivaraj it will compile it but not the way you want it to be compiled. Check your compiled javascript file. – eko Nov 25 '16 at 12:18
  • 1
    Thanks For Your Help @GünterZöchbauer @ echonax – Yuvaraj V Nov 25 '16 at 14:24
  • actually i change the plukr and it works ! model = { name:"hi"}; – Kross Oct 24 '17 at 11:59