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..
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..
Please Kindly Explain Difference Between Two Code Samples and Why It's Not Working in Second Sample..
Thanks In Advance.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With