簡體   English   中英

檢測由父 angular 2 觸發的子組件變量的變化

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

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

我正在從應用程序向孩子發送一個變量,我想檢測變量中的任何變化並相應地顯示數據。 我無法檢測到變量的變化。

任何幫助? 我附上了Plunker鏈接,我還在評論中解釋了我想在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 鏈接

要么將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

支持所有類型的值。

這是更新 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

你必須像這樣進行綁定:

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

對於組件之間通信的不同方法,這是一個非常好的資源:

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

您正在尋找的是:使用輸入綁定將數據從父級傳遞給子級

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM