如何在Angular 4中检测@Input()绑定与用户定义类型的更改

时间:2018-04-23 11:46:23

标签: angular ngonchanges

以下是我正在做的示例代码。

模型组件

//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;
        }
}

子组件中未检测到文本框文本更改。

Live Demo

2 个答案:

答案 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)

您可以通过两种方式选择

  • 使用ngOnChanges
  • 使用来自typescript的getter和setter

宣读more here

Working example