-2

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

模型组件

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

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

现场演示

4

2 回答 2

0

您可以使用 ngOnChanges ( https://angular.io/api/core/OnChanges )观察输入变化

class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

编辑 更改属性名称时不会修改您的值 emp,因此在子组件中未检测到任何更改。你能做的就是只传递财产

@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";
  }

}

@Component({
  selector: 'hello',
  template: `<h1>{{displayName}}</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})

export class HelloComponent implements OnChanges  {
  @Input() name: String;
  displayName:string;
  ngOnChanges(changes: SimpleChanges) {
        console.log('Life cycle hook method called.');
        this.displayName='Hello, '+this.name;
        }
}
于 2018-04-23T11:48:36.180 回答
0

您可以选择两种方式

  • 使用 ngOnChanges
  • 使用打字稿中的 getter 和 setter

在这里阅读更多

Working example

于 2018-04-23T11:56:27.697 回答