[英]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 这是我的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 还有我的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. 问题是,“ N现在是#”应该实时更改我键入的内容。 But the changing seemed never pass to AppComponent. 但是更改似乎从未传递给AppComponent。 N just remained 1 as initial. N最初保留为1。 How can I make values of mynumber
change when I type and change affect the function too? 当我键入内容时,如何更改mynumber
值,并且更改也会影响函数?
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. N被分配了this.mynumber
的当前值,即1。更改mynumber
时,其值不会自动更新。 You can either a) ditch the redundant property N
and just use mynumber
, or b) update N
it every time mynumber
is updated. 您可以a)放弃冗余属性N
并仅使用mynumber
,或者b)每次更新mynumber
都对其进行更新N
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
. 将N
的值初始化为mynumber
它只会发生一次,并且不会反映对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
: 要使其工作,您可以对ngModelChange
进行事件绑定,并破坏[[x)]语法,并在组件中触发一个方法,该方法将在mynumber
更改时更新N
的值:
<input [ngModel]="mynumber" (ngModelChange)="valuechange($event)">
N is now {{N}}
And in the component, update N
when the method is triggered: 并在组件中,在触发方法时更新N
:
valuechange(value){
this.N = value;
}
Although this approach is redundant and you can simply use the mynumber
in the template expression. 尽管这种方法是多余的,并且您可以简单地在模板表达式中使用mynumber
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.