I have created a component in Angular 5 that will house a reusable template for a button. In different parts of my app buttons will call different functions, so I would like to be able to tell the given instance of the button what function to call.
You have to use the
@Output
decorator to emit some event (from child to parent)
button.component.ts:
import { Component, Output, EventEmitter, Input } from '@angular/core';
@Component({
selector: 'app-button',
templateUrl: './button.component.html'
})
export class ButtonComponent {
@Input() label: string;
@Output() onClick = new EventEmitter<any>();
constructor() {}
onClickButton(event) {
this.onClick.emit(event);
}
}
button.component.html:
<div id="button">
<button type="button" class="btn" (click)="onClickButton($event)">
{{ label }}
</button>
</div>
parent.component.ts
import { Component, Output, EventEmitter, Input } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent {
label: string = "RandomButtonLabel"
constructor() {}
functioncall(event) {
console.log('functioncall', event);
}
}
parent.component.html
<app-button (onClick)="functioncall($event)" [label]="label"></app-button>
1 Comments
Thanks for this blog
ReplyDelete