While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action.
I'm wondering if there is a way to directly pass the 'onDiscard' event handler received in FormComponent to FormActionsComponent without having to create a new handler for it?
It would be great if I could avoid writing two event handlers and emitting the event twice.
FormComponent:
@Component({
selector: 'app-form',
template: `
<form [formGroup]="nametagForm" (ngSubmit)="handleSubmit()">
...
<app-form-actions (onDiscard)="handleDiscard()"></app-form-actions>
</form>
`,
styleUrls: []
})
export class FormComponent implements OnInit {
...
@Output()
onDiscard = new EventEmitter<void>()
handleDiscard(): void { this.onDiscard.emit() }
}
FormActionsComponent:
@Component({
selector: 'app-form-actions',
template: `
<div class="form-actions">
<button (click)="handleDiscard()" type="button">Discard</button>
<button [disabled]="formControl.invalid" type="submit">Save</button>
</div>
`,
styleUrls: []
})
export class FormActionsComponent implements OnInit {
private formControl: FormGroup
@Output()
onDiscard = new EventEmitter<void>()
constructor(private readonly rootFormGroup: FormGroupDirective) { }
ngOnInit(): void {
this.formControl = this.rootFormGroup.control
}
handleDiscard(): void { this.onDiscard.emit() }
}
Some Parent Component:
@Component({
selector: 'app-parent',
templateUrl: `
<app-form ... (onDiscard)="handleDiscard()"></app-form>
`,
styleUrls: []
})
export class ParentComponent implements OnInit {
...
handleDiscard(): void { // do something ... }
}