Detect change in child component variable caused by parent angular 2

I have 2 files. app.ts and child.ts

I am sending a variable from the application to the child, and I want to detect any change in the variable and show the data accordingly. I cannot detect changes in a variable.

Any help? I plugged in Plunker Link and I also explained what I want to do in the Child.ts file in the comments

App.ts File

//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 file

 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

+6
source share
3 answers

Either you make a newData setter, or implement 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

hint

 newdata={{data}} 

excellent, but only supports string values

 [newdata]=data 

supports all types of values.

Here is a link to the updated plnkr to explain the same thing, https://plnkr.co/edit/5ahxWJ?p=preview

+4
source

Some code changes can do the same job.

1) provide newData as input and do not use interpolation to pass data to a child component.

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

2). Two easy ways to detect changes are ngOnChanges, as @Gunter suggests, or using rxjs. Observable Subscriber Model Lightweight, which is ngOnChanges. Here is your modified plunkr using the same. https://plnkr.co/edit/5ahxWJ?p=preview

+2
source

You need to do the binding as follows:

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

These are really good resources for different methods of communication between components:

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

What you are looking for is: Pass data from parent to child with input binding

0
source

Source: https://habr.com/ru/post/1014231/


All Articles