tamim abweini
tamim abweini

Reputation: 431

angular: access ng-content nested component method from outside

I have two shared components and I want the parent to invoke a method in its child

shared component 1 (parent)

@Component({
selector: 'parent',
template: `<div>
                <div #parentBody>
                   <ng-content select="[parentBody]"></ng-content>
                </div>
                <button (click)=" " >tell child to dance</button>
            </div>
        `,
})
export class ParentComponent {
  constructor() { }

}

shared component 2 (child)

@Component({
selector: 'child',
template: `<div>
                <p>I'm a child component</p>
           </div>
          `,
})
export class ChildComponent {
  dance() {
     alert('dancing');
  }
}

and in app component

<parent>
    <div parentBody>
       <child></child>
    </div>
<parent>

how can we communicate between the parent and child component in this case

Upvotes: 2

Views: 5506

Answers (1)

benshabatnoam
benshabatnoam

Reputation: 7632

You can do it in 2 ways:

1) @Output parameter in parent component.

parent.component.ts:

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'parent',
  template: `
    <div>
      <div #parentBody>
        <ng-content select="[parentBody]"></ng-content>
      </div>
      <button (click)="dance.emit()">tell child to dance</button>
    </div>
  `
})
export class ParentComponent {
  @Output() dance = new EventEmitter();
}

app.component.html:

<parent (dance)="myChild.dance()">
    <div parentBody>
       <child #myChild></child>
    </div>
<parent>

Check this simple StackBlitz DEMO which is using @Output approach


2) @ContentChild parameter in parent component.

(Added after @trichetriche commented this question. thanks @trichetriche!)

parent.component.ts:

import { Component, Input, ContentChild } from '@angular/core';

import { IChild } from './i-child';

@Component({
  selector: 'parent',
  template: `
    <div>
      <div #parentBody>
        <ng-content select="[parentBody]"></ng-content>
      </div>
      <button (click)="onClick()">tell child to dance</button>
    </div>
  `
})
export class ParentComponent {
  @ContentChild('myChild') child: IChild;

  onClick() {
    this.child.dance();
  }
}

app.component.html:

<parent>
    <div parentBody>
       <child #myChild></child>
    </div>
<parent>

Check this simple StackBlitz DEMO which is using @ContentChild approach


Either ways are a good solution to your requirement.

Upvotes: 5

Related Questions