Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

Passing/emitting events through to parent component?

In Angular I can create a child component that emits an action:

@Component({
   ...
    template: `
      <button (click)='someAction($event)'>Click Me</button>
    `
})
export class ChildComponent {

    @Output() onChildAction = new EventEmitter();

    childAction() {
      this.onChildAction.emit();
    }
}

and a parent component to handle it. Something like:

@Component({
    ...
    template: `
      <child-component (onChildAction)="parentAction()"></child-component>
    `
})
export class ParentComponent {
    parentAction() {
      console.log('Hello');
    }
}

This works fine, but is there a way to "passthrough" the action directly to the parent without having to create a click handler in the child that calls .emit()?

Something like:

@Component({
   ...
    template: `
      <button (click)='onChildAction.emit($event)'>Click Me</button>
    `
})
export class ChildComponent {
    @Output() onChildAction = new EventEmitter();
}

and:

@Component({
    ...
    template: `
      <child-component (onChildAction)="parentAction()"></child-component>
    `
})
export class ParentComponent {
    parentAction() {
      console.log('Hello');
    }
}

where the event is immediately emitted to the parent without having to go through a child handler. This is useful when you have simply click events in the child that you want to let the parent component handle.

Upvotes: 0

Views: 1710

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29695

It is definitely possible to emit events from the template file. In fact I do the same when it is a single line code. This is easy to read as well.

<button (click)='onChildAction.emit($event)'>Click Me</button>

Here is a DEMO

Upvotes: 1

Related Questions