2017-01-19 48 views
6

我有2个文件。 app.ts和Child.ts检测由父角度触发的子组件变量的更改2

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

任何帮助?我重视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 value of control in newdata variable is false 
    // then display message on front end "your controls are not working" 
    // if value of control in newdata variable is true 
    // then display message on front end "your controls are working fine." 
    // this should automatically happen whenever I change the value of newdata variable 
} 

Plunker Link

回答

4

您可以将newData设为埃特或您实现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

非常感谢您的帮助。 ngOnChanges为我工作。并感谢提示。 – amansoni211

2

一些代码的修改可以使同样的工作。

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

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

2)两种简单的方法来检测变化是由ngOnChanges作为@Gunter建议或使用rxjs可观察订户模型,易于一个是ngOnChanges。这是你修改后的plunkr使用相同的。 https://plnkr.co/edit/5ahxWJ?p=preview

+1

你的佣兵帮了很多。谢谢! – amansoni211