【发布时间】:2018-07-17 04:08:52
【问题描述】:
每当组件生命周期或模板中的变量 this.test 发生更改但它不起作用时,我试图在我的 Angular 5.x 组件中调用函数 ngOnChanges() 但它不起作用,ngOnChanges() 函数不会随时调用。请问有人可以帮我吗?
src/app.ts:
import {Component, NgModule, Input, OnChanges, SimpleChanges} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Test field" value="{{ test }}">
</div>
`,
})
export class App implements OnChanges {
@Input() test: string;
name: string;
constructor() {
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges');
if (changes.test && !changes.test.isFirstChange()) {
// exteranl API call or more preprocessing...
}
for (let propName in changes) {
let change = changes[propName];
console.dir(change);
if(change.isFirstChange()) {
console.log(`first change: ${propName}`);
} else {
console.log(`prev: ${change.previousValue}, cur: ${change.currentValue}`);
}
}
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
实时预览:https://plnkr.co/edit/ZHFOXFhEkSv2f1U3lehv
非常感谢!
【问题讨论】:
-
我在您的链接插件中看到模板解析错误。它不喜欢你的
ngModel用法
标签: javascript angular typescript ngonchanges