Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 563
Yuvaraj V Avatar asked Oct 18 '22 21:10

Yuvaraj V


1 Answers

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";
}
like image 179
eko Avatar answered Oct 21 '22 02:10

eko