2

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>.

2 Answers 2

4

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."

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

10 Comments

But then CardComponent needs to be aware of ComponentA right?
@Салман Assuming CardComponent is ComponentA's parent: yes.
Hmm... As I shown in the question, CardComponent can be used to wrap any component, in which case it is not possible for CardComponent to know all the possible children
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.
@GünterZöchbauer @ContentChild also need the ComponentA reference as its param right?
|
1

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>

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.