9

My requirment is to fire event from the code to a parent hosting component.

I used the first answer here as a reference: angular2 manually firing click event on particular element

If I try this, it works well:

this.itemHost.viewContainerRef.element.nativeElement.dispatchEvent(new Event('click'));

In the parent component I wrote this:

(click)="go()"

It arrives to the go method when the above code occurs.

But this doesn't work if I do it with some custom event name, e.g.:

this.itemHost.viewContainerRef.element.nativeElement.dispatchEvent(new Event('customEvent'));

and in the parent component:

(customEvent)="go()"

How can I do it with custom event?

2
  • You have to use the Output() decorator Commented Jul 25, 2017 at 8:34
  • I tried and didn't success with it. can you giv eme example how to declare it? Commented Jul 25, 2017 at 8:38

2 Answers 2

18

Your event is not bubbling. Try it:

.dispatchEvent(new Event('customEvent', { bubbles: true }));

Plunker Example

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

5 Comments

Can I pass event args here too?
Yes, use detail
where do I put it?
2

Use @Output() to have custom events inside your components. In the example below it is triggered while clicking on a div, but you can obviously have it emit whenever. Try to avoid the use of nativeElement as much as possible, because this will prevent running your application in any other environment, but the browser

parent

@Component({
   selector: 'parent',
   template: `<child (customEvent)="onCustomEvent($event)"></child>`
})
export class ParentComponent {

  onCustomEvent(response: string): void {
    console.log(response);
  }
}

child

@Component({
   selector: 'child',
   template: `<div (click)="customEvent.emit('blabla')"></div>`
})
export class ChildComponent {

  @Output()
  customEvent: EventEmitter<string> = new EventEmitter<string>();
  
}

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.