Search code examples
angularinputngmodel

Angular2 ngModel-var value does not same like this.var value


I have some strange behavior by my ngModel-values within child-component. html-code:

<input type="text" pattern="^[a-zA-Z]$"
                           class="form-control" required="true"
                           id="myId" 
                           [(ngModel)]="kName">

kName is an input field (@kName:string), which will be filled from parent-component. I can see that "this.kName" gets everytime new value from parent-component. But when I set after some actions on this field on:

this.kName = undefined;

And then I want to fill kName again from parent, my kName-current value will not appear on html-output, but I can see on: this.kName When I try to do like this:

<input type="text" pattern="^[a-zA-Z]$"
                           class="form-control" required="true"
                           id="myId" 
                           [(ngModel)]="{{this.kName}}">

I get error on init by html-pattern, because kName is undefined. How can I refresh my ngModel-value? Maybe I have some other problems...


Solution

  • Seems like you have another problem anywhere..

    Are there any error messages in you console?

    Take a look at this plunker, works as expected: https://plnkr.co/edit/2VUOimDCMvPSNHD1mX69?p=preview

    You can "clear" it and rewrite it from parent-component..

    import {Component, NgModule, Input} from '@angular/core'
    import {FormsModule} from '@angular/forms'
    import {BrowserModule} from '@angular/platform-browser'
    
    @Component({
      selector: 'my-child',
      template: `
        <input [(ngModel)]="kName" />
        <button (click)="clearFunction()">clear</button>
        <br />
        {{kName}}
      `,
    })
    export class Child {
      @Input() kName: string;
    
      constructor() { }
    
      clearFunction() {
        this.kName = undefined;
      }
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2 (click)="changeSomething()">Hello {{name}}</h2>
          <my-child [kName]="myKname"></my-child>
        </div>
      `,
    })
    export class App {
      name:string;
      myKname: string;
    
      constructor() {
        this.name = 'Angular2'
      }
    
      changeSomething() {
        this.myKname = Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
      }
    }
    
    @NgModule({
      imports: [ BrowserModule, FormsModule ],
      declarations: [ App, Child ],
      bootstrap: [ App ]
    })
    export class AppModule {}