Salman
Salman

Reputation: 9447

Angular2: call child component method

I have a component called CardComponent with following markup

<div class="header">
    <!-- My card style header -->
</div>

<div class="content">
    <ng-content></ng-content>
<div>

<div class="footer">
    <!-- My card style footer -->
    <!-- Need a button here (explained below) -->
</div>

I'm using this as following

<card>
    <component-a></component-a>
</card>

<card>
    <component-b></component-b>
</card>

It works fine. However, I need to add a button in the card footer which will call a method of the respective child component.

For example, the button on the first card will call a function in component-a and the second in component-b.

can I do this without a pipeline in my main/container component? and also without the need to do a <component-a #var>.

Upvotes: 2

Views: 1559

Answers (2)

eko
eko

Reputation: 40647

You can do this by using @ViewChild in your parent component:

@ViewChild(ComponentA) theComponent: ComponentA;

where ComponentA is the reference of your component name.

Then you can use child components methods with this field,

theComponent.method()

As suggested by @Günter:

"If it's passed to <ng-content> you need to use @ContentChild() instead of @ViewChild(). @ViewChild() only looks up elements in the template. You also should mention that theComponent won't be set before ngAfterContentInit() is called."

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657108

You can add an EventEmitter (doSomething) to your CardComponent that emits an event when the button is clicked and then

<card (doSomething)="componenta.aFunction()">
    <component-a #componenta></component-a>
</card>

<card (doSomething)="componentb.aFunction()">
    <component-b #componentb></component-b>
</card>

Upvotes: 1

Related Questions