Emit an event dynamically in angular

763 Views Asked by At

I am trying to create a child component where I want to emit an event to the parent based on some condition.

For simplicity's sake, let's say that I have a child component and will take an input(boolean), and based on that input I want to, later on, emit an event.

<child-component
  [canEmitValue]="false"
  (emitValue)="someMethod()" //I want to add this emitValue based on the input.
>
</child-component>

We're trying to create a reusable component and we want to hide the the event based on something.

Questions:

  • Is there a way to add the event dynamically i.e add the behaviour of @Output without implicitly specifying the @Output
  • If not, is there any suggestions
2

There are 2 best solutions below

1
On

Is there a way to add the event dynamically i.e add the behaviour of @Output without implicitly specifying the @Output

No that's not the concept of input/output binding in Angular. Read more here: https://angular.io/guide/inputs-outputs

In the parent template the event binding (emitValue)="someMethod($event)" connects the event in the child to the parent.

What I understand you're basically trying to 'disable' the component. In that case; the output event emitter inside the child component should check the input value and not emit anything to the parent.

Alternatively you can try, which I do not recommend:

<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>
    Content to render when condition is true.
    <child-component [canEmitValue]="condition" (emitValue)="someMethod()"></child-component>
</ng-template>
<ng-template #elseBlock>
    Content to render when condition is false.
    <child-component [canEmitValue]="condition" ></child-component>
</ng-template>
0
On

To add a custom event based on something I found out that you can:


constructor(
    private el:ElementRef
  ) {  }


 ... some code

 public someMethodThatChecksSoething(){

   this.el.nativeElement
        .dispatchEvent(new CustomEvent('todo', {
          detail: value,
          bubbles: true
        }));
}