Danielle
Danielle

Reputation: 1496

Get a variable in child from parent, triggering it from the parent component

I am having a hard time understanding this.

I have a component I pass a variable to as follows:

 <app-selectcomp [plid]="plid" [codeId]="selectedCode" (notify)="getCompFromChild($event)"></app-selectcomp>

Im passing two variables: plid and codeId.

With these two variables, there are some user actions that create an array called response.data

I was able to send response.data to the parent component as follows:

@Output() notify: EventEmitter<string> = new EventEmitter<string>(); 
this.notify.emit(this.response.data)

And then, on the parent component

getCompFromChild(values): void {}

All this works fine, except that in order to get the data at the parent component, I have to trigger it from the child component with, for example, with a button click.

I cannot find a way to get the value for response.data, which exists at the child component, but straight from the parent component, for example by clicking a button on the PARENT component.

<button type="submit" (click)="getDatainChild()">Get Child Data</button>

Thanks.

Upvotes: 3

Views: 2501

Answers (1)

Dorin Baba
Dorin Baba

Reputation: 1738

You can use @ViewChild() to get the desired behavior by having a reference to child component from parent. Following this approach, parent will able to call public methods of child component. Something like this:

In your parent component (.ts):

@ViewChild('selectComp') selectComp: SelectComponent; <= specify the type of your child component

In your parent component (.html)

<app-selectcomp #selectComp [plid]="plid" [codeId]="selectedCode" 
       (notify)="getCompFromChild($event)">
</app-selectcomp>

In your child component (.ts) Create a method that will be called by the parent

public getData() { }

Now, you can call the getData() method of child component within parent component.

selectComp.getData();

Upvotes: 2

Related Questions