以下是我正在做的示例代码。
模型组件
//app.models.ts
export class Employee{
Name:string;
Salary:number;
}
根组件
//app.component.ts
import { Component } from '@angular/core';
import { Employee } from './app.models.ts';
@Component({
selector: 'my-app',
template: '<input type="text" [(ngModel)]="emp.Name"><hello [employee]="emp"></hello>'
})
export class AppComponent {
emp:Employee;
constructor(){
this.emp=new Employee();
this.emp.Name="Neeraj";
}
}
子组件
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Employee } from './app.models.ts';
@Component({
selector: 'hello',
template: `<h1>{{displayName}}</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnChanges {
@Input() employee: Employee;
displayName:string;
ngOnChanges(changes: SimpleChanges) {
console.log('Life cycle hook method called.');
this.displayName='Hello, '+this.employee.Name;
}
}
子组件中未检测到文本框文本更改。
答案 0 :(得分:0)
您可以使用ngOnChanges(https://angular.io/api/core/OnChanges)
观看输入更改ii A.1 A.2 B.1 B.2
1 Ly bar Xy mat
2 Ab zul Ko foo #notice, this is unchanged because A.1 B.1 are already sorted
EDIT 更改属性名称时不会修改值emp,因此不会在子组件中检测到任何更改。你能做的只是通过财产
class MyComponent implements OnChanges {
@Input()
prop: number;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
并且
@Component({
selector: 'my-app',
template: '<input type="text" [(ngModel)]="emp.Name"><hello [name]="emp.Name"></hello>'
})
export class AppComponent {
emp:Employee;
constructor(){
this.emp=new Employee();
this.emp.Name="Neeraj";
}
}
答案 1 :(得分:0)