Yuvaraj V
Yuvaraj V

Reputation: 1212

Angular 2 ngModel Not Binding Object Property Defined In Class Definition

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.

Upvotes: 5

Views: 13884

Answers (1)

eko
eko

Reputation: 40647

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";
}

Upvotes: 3

Related Questions