Creating a reusable button component in Angular

you have to use the @Output decorator to emit some event (from child to parent)

button.component.ts:

@Input() label: string;
@Output() onClick = new EventEmitter<any>();

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

label = "button label"

  functioncall(event) {
    console.log('functioncall', event);
  }

parent.component.html

<app-button (onClick)="functioncall($event)" [label]="label"></app-button>

See example: https://stackblitz.com/edit/angular-gghsax


In addition to @miladfm answer, I'd recommend using the <ng-content></ng-content> directive here to pass content through instead of pulling in {{label}}, assigning the @Output decorator to click instead of onClick, and using the MouseEvent type instead of any. Using these changes will allow the button component to behave syntactically more like a native button when it's consumed:

button.component.ts

...
@Output() click = new EventEmitter<MouseEvent>();

onClickButton(event) {
  this.onClick.emit(event);
}
...

button.component.html

<div id = "button">
  <button type="button" class="btn" (click)="onClickbutton($event)">
    <ng-content></ng-content>
  </button>
</div>

parent.component.ts

...
functioncall(e: MouseEvent) {
 // do stuff
}
...

parent.component.html

<app-button  (click)="functioncall($event)">Your Label Here</app-button>

Tags:

Button

Angular