我正在尝试通过实验来学习角2,我发现ngOnChanges不会在下面的代码中触发:
app.component.ts:
import { Component, Input } from "@angular/core"
import { FormsModule } from '@angular/forms';
import { OnChanges, SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector: 'my-app',
template: `
Enter text : <input type="text" [(ngModel)]='userText' />
<br/>
Entered text : {{userText}}
`
})
export class AppComponent {
@Input() userText: string;
name: string = "Tom";
ngOnChanges(changes: SimpleChanges): void {
for (let propertyName in changes) {
let change = changes[propertyName];
let current = JSON.stringify(change.currentValue);
let previouis = JSON.stringify(change.previousValue);
console.log(propertyName + ' ' + current + ' ' + previouis);
}
}
}以上代码不会触发ngOnChanges
然而,如果我创建一个单独的“简单”组件并在中使用它,那么下面的工作是:
app.component.ts:
import {Component} from "@angular/core"
import {FormsModule} from '@angular/forms';
@Component({
selector: 'my-app',
template: `
Enter text : <input type="text" [(ngModel)]='userText' />
<br/>
<simple [simpleInput]='userText'></simple>
`
})
export class AppComponent{
userText:string;
name:string ="Tom";
}simple.component.ts:
import {Component,Input} from '@angular/core';
import { OnChanges,SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector:'simple',
template: `You entered {{simpleInput}} `
})
export class SimpleComponent implements OnChanges{
ngOnChanges(changes: SimpleChanges): void {
for(let propertyName in changes){
let change=changes[propertyName];
let current=JSON.stringify(change.currentValue);
let previouis=JSON.stringify(change.previousValue);
console.log(propertyName+ ' '+current+ ' ' +previouis);
}
}
@Input() simpleInput: string;
}有谁能解释一下吗?我在这里做错什么了?
发布于 2018-04-08 11:13:41
我认为您可能误解了“输入字段”的意图。@输入字段允许父组件和子组件之间进行通信,组件中的数据库不需要它们。数据库不需要任何属性,字段必须是公共的。作为一个生命周期钩子,ngOnChanges的目的是对@输入字段上的更改做出反应,而不是对html输入元素作出反应。
如果您想要比双向绑定更精细的更改行为,请尝试。
<input type="text" [(ngModel)]='userText' (ngModelChange)="onUserTextChange($event)">
(很抱歉,如果上面的代码不能正常工作,我一回到开发人员机器上就会立即测试和清理)
您可以找到更多的信息这里。
https://stackoverflow.com/questions/49716105
复制相似问题