javascript – 处理Angular 5组件中的模型更改(双向绑定)
作者:互联网
我目前正在开发一个角度5应用程序.我尝试在视图的输入中更改组件的成员变量,并在更改后使用组件中的变量.
我的结构如下:
文件夹:my-test
> my-test.component.html
> my-test.component.css
> my-test.component.ts
1)my-test.component.html:
<input [(ngModel)]="hello" />
2)my-test.component.ts:
import { Component, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'my-test',
templateUrl: './my-test.component.html',
styleUrls: ['./my-test.component.css']
})
export class MyTestComponent implements OnChanges {
hello: string = "bonjour";
constructor() { }
ngOnChanges(changes: SimpleChanges) {
// I'd like to log the changes of my field 'hello',
// once it get's changed in the input on the ui...
console.log(changes);
}
}
不幸的是,这个解决方案无效.你知道如何在ui上更改组件的变量,然后在组件中使用它吗?
谢谢!!
解决方法:
您可以使用(ngModelChange)指令
<input [(ngModel)]="hello" (ngModelChange)="myFunction()"/>
码:
import { Component } from '@angular/core';
@Component({
selector: 'my-test',
templateUrl: './my-test.component.html',
styleUrls: ['./my-test.component.css']
})
export class MyTestComponent {
hello: string = "bonjour";
constructor() { }
myFunction() {
console.log(this.hello);
}
}
标签:javascript,html5,angular,angular-components,two-way-binding 来源: https://codeday.me/bug/20190611/1216199.html