Collierre
Collierre

Reputation: 956

How to access methods in arbitrary Angular child component projected with <ng-content>?

I'm making a dialog with Angular Material that will be a parent component (containing the dialog header and footer) that can then project an arbitrary child component (dialog content) using <ng-content>/ng-content>.

dialog.component.html:

<h1 mat-dialog-title>Title</h1>
<mat-dialog-content>
  <ng-content></ng-content>
</mat-dialog-content>
<mat-dialog-actions>
  <button mat-icon-button (click)="submit()">
    <mat-icon>save</mat-icon>
  </button>
</mat-dialog-actions>

arbitrary-dialog-content.component.html

<dialog>
  <!-- Dialog content here -->
</dialog>

What I want to do is to call the arbitrary-dialog-content's save() method FROM the dialog's save() method, so I need to get a reference to the arbitrary component from the parent component. I've tried using @ContentChild but can't get it to work because I don't know which component will be the dialog content until runtime.

Upvotes: 0

Views: 301

Answers (1)

bryan60
bryan60

Reputation: 29355

you can use an event emitter on your dialog component to communicate between components.

add this in your dialog.ts:

@Output() onSubmit = new EventEmitter();

submit() {
  // do whatever you want
  this.onSubmit.next();
}

then in your arbitrary component html:

<dialog (onSubmit)="save()">
  <!-- Dialog content here -->
</dialog>

where save() is your components save function

a shared service would be a more comprehensive solution but this works for this use case.

Upvotes: 1

Related Questions