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.

1 Answer 1

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";
}
Sign up to request clarification or add additional context in comments.

7 Comments

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
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.
@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.
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 ?
Thanks For Your Help @GünterZöchbauer @ echonax
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.