Reputation: 53971
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
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