检测由 parent angular 2 触发的 child 组件变量的变化

Detect change in child component's variable triggered by parent angular 2

我有 2 个文件。 app.ts 和 Child.ts

我正在将一个变量从应用程序发送到 child,我想检测变量中的任何变化并相应地显示数据。我无法检测到变量的变化。

有帮助吗?我附上了 Plunker Link,我还在评论 Child.ts 文件中解释了我想做什么

App.ts 文件

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ChildCom} from './child.ts'

@Component({
    selector: 'my-app',
    template: `
    <div>
        <h2>Hello</h2>
        <child-com newdata={{data}}></child-com>
    </div>
    `,
})
export class App {
    data: any = [];

      constructor(){
          this.data = [{"name":"control","status":"false"}];
    }
}

@NgModule({
    imports: [ BrowserModule ],
    declarations: [ App, ChildCom ],
    bootstrap: [ App ]
})
export class AppModule {}

Child.ts 文件

import {Component, Input} from '@angular/core';

@Component({
  selector: 'child-com',
  template: `
    <div>
      <p>Controls: {{newdata}}</p>
    </div>
  `,
})

export class ChildCom {
  @Input() newdata: any = [];

  constructor(){
  }

  // here I want to check if the value of control in newdata variable is false 
  // then display a message on the front end "your controls are not working"
  // if the value of control in newdata variable is true
  // then display a message on front end "your controls are working fine."
  // this should automatically happen whenever I change the value of newdata variable
}

Plunker Link

你必须这样绑定:

<child-com [newdata]="data"></child-com>

对于组件间通信的不同方法,这是一个非常好的资源:

https://angular.io/docs/ts/latest/cookbook/component-communication.html

您正在寻找的是:使用输入绑定将数据从父级传递给子级

要么将 newData 设为 setter,要么实施 OnChanges

export class ChildCom {
  private _newdata: any = [];
  @Input() 
  set newdata(value) {
    // code here
  }
}
export class ChildCom implements OnChanges {
  @Input() set newdata(: any = [];

  ngOnChanges(changes) {
    // code here
  }
}

https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html

提示

newdata={{data}}

很好,但只支持字符串值

[newdata]=data

支持所有类型的值。

这里是 link 更新的 plnkr 解释相同,https://plnkr.co/edit/5ahxWJ?p=preview

一些代码更改可以实现相同的工作。

1) 提供 newData 作为输入,不使用插值将数据传递给子组件。

<child-com [newdata]="data"></child-com>

2) 两种检测变化的简单方法是@Gunter 建议的 ngOnChanges 或使用 rxjs Observable 订阅者模型,简单的方法是 ngOnChanges。这是您使用相同的修改后的 plunkr。 https://plnkr.co/edit/5ahxWJ?p=preview