我试图在我的Angular 5.x组件中调用函数ngOnChanges()
,只要组件生命周期或模板中的变量this.test
发生变化但它不起作用,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
非常感谢!
答案 0 :(得分:4)
输入属性为父组件提供了一种将数据传递给子组件的机制。它们并不意味着将数据从模板传递到其组件。
只有对PARENT定义的输入属性的更改才会生成onChanges方法。
我更新了plunker来修复缺少的FormsModule并添加一个子组件来演示如何使用input属性和onChanges生命周期钩子:
https://plnkr.co/edit/1JF0wV28HnjXDZxMSifY?p=preview
子组件
@Component({
selector: 'my-child',
template: `
<div>
<input type="text" [(ngModel)]="test" placeholder="Test field">
</div>
`,
})
export class ChildComponent implements OnChanges {
@Input() test: string;
name: string;
constructor() { }
ngOnChanges(changes: SimpleChanges) {
console.log('in 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}`);
}
}
}
}
父组件
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<my-child [test]='parentTest'></my-child>
<button (click)='onClick()'>Change Value</button>
</div>
`,
})
export class App {
parentTest: string;
name: string;
counter = 1;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
onClick() {
this.parentTest = `test: ${this.counter}`;
this.counter++;
}
}
要从模板组件中的模板中捕获更改,请改用setter:
// To catch changes from the template
_test: string;
get test(): string {
return this._test;
}
@Input()
set test(value: string) {
this._test = value;
console.log("Textbox value changed: " + this._test);
}
或者您可以使用Sajeetharan的建议来捕捉模板在其关联模板中的更改。它也会工作。
答案 1 :(得分:4)
这里你需要的是ngModelChange而不是ngOnChanges
<input type="text" placeholder="Test field" (ngModelChange)="printVal()">
然后
printVal(){
//detect model change here
}
ngOnChanges
适用于@input事件发射器