简体   繁体   中英

Angular 6 ngModel didn't change value in appcomponent

I am now practicing angular & typescript and facing some simple problem.

Here is my component.html

<div>
    <input [(ngModel)]="mynumber">
    N is now {{N}}
    // some content I want to do with functions with changing mynumber
</div>

And my component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
    mynumber = '1';
    N = this.mynumber;
    // some function with mynumber
}

The problem is, "N is now #" should change whatever I type at real time. But the changing seemed never pass to AppComponent. N just remained 1 as initial. How can I make values of mynumber change when I type and change affect the function too?

During the execution of the line

N = this.mynumber;

N is assigned the current value of this.mynumber , that is, 1. Its value isn't automatically updated when mynumber is changed. You can either a) ditch the redundant property N and just use mynumber , or b) update N it every time mynumber is updated.

When you initialize the value of N to mynumber it happens only once and won't reflect the new changes to the value of mynumber .

To make it work you can do a event binding to ngModelChange and break up the [(x)] syntax and trigger a method in the component which will update the value of N on change of mynumber :

<input [ngModel]="mynumber" (ngModelChange)="valuechange($event)">
  N is now {{N}}

And in the component, update N when the method is triggered:

 valuechange(value){
    this.N = value;
 }

Although this approach is redundant and you can simply use the mynumber in the template expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM