0

I'm having two child components and referring from parent and I'm trying to update @Input object after child component initialized

.html:

<div>
 <app-child-one></app-child-one>
 <app-child-two [data]="test"></app-child-two>

 <button (click)="onClick()">Clicked</button>
</div>

.ts:

test: string;

onClick() {
  this.test = 'Hello World !!';
}

By the time I clicked on the button both the child components are initialized, how could I update the data property value to the child component after clicking the button ??

3
  • Are you using any change detection strategy on your <app-child-two> component ? Commented Jul 16, 2019 at 2:43
  • I've ngAvfterViewInIt() no other detection strategy and looks like it's not helping much.. Commented Jul 16, 2019 at 4:38
  • You just copy one of your child component in your question Commented Jul 16, 2019 at 6:13

1 Answer 1

1

Using @ViewChild you can achive this. Add id #appChildTwo in

<div>
 <app-child-one></app-child-one>
 <app-child-two [data]="test" #appChildTwo></app-child-two>

 <button (click)="onClick()">Clicked</button>
</div>

In .ts file of parent

import {  ViewChild } from '@angular/core'; 

Declare class variable in parent

@ViewChild('appChildTwo') appChildTwo; 

on button click. By using viewchild we get reference of the child component in parent's component file and then we can access all public member and function of child component using viewchild refernce.

onClick() {
 this.test = 'Hello World !!';
if(this.appChildTwo)
  this.appChildTwo.data= 'Hello World !!';
}

Hope this will help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.