0

I want to populate the button click from interface value for example

interface IButton {
    buttonClickValue: string
}

export class Button implements OnInit {
     toolBar: IButton = {
       buttonClickValue: "onCML"    //I also tried this onCML()
     }
     constructor() {}

    ngOnInit(): void {          
    }

    onCML(){    
      alert("Alert should appear on click!!!");
    }

 }   

Here is my frontEnd button where I would like to bind the interface value to the button click

<a class="btn btn-primary" (click)="toolBar.buttonClickValue">My Button</a>

However when I click on the button nothing happens I would like to see the alert. Thank you for your help.

J.C
  • 632
  • 1
  • 10
  • 41

2 Answers2

2

The return type for buttonClickValue should match the function.

interface IButton {
  buttonClickValue: () => void;
}

export class Button implements OnInit {
  toolBar: IButton = {
    buttonClickValue: this.onCML,
  };
  constructor() {}

  ngOnInit(): void {}

  onCML() {
    alert("Alert should appear on click!!!");
  }
}

Edit: I believe you'll also need to invoke said function in the template:

<a class="btn btn-primary" (click)="toolBar.buttonClickValue()">My Button</a>
John
  • 1,240
  • 9
  • 13
  • 1
    Thank you, thank you it is exacly what I wanted. I can accept your anwser in 6 minutes. – J.C Apr 13 '21 at 11:24
1
  1. Define a callback type to the buttonClickValue property instead of string.
  2. Assign the onCML callback using this.onCML or an arrow function. If you intend to use this keyword inside the callback to refer to class member variables, you either need to bind using this.onCML.bind(this) or use an arrow-function (Canonical answer).
import { Component, OnInit } from "@angular/core";

interface IButton {
  buttonClickValue: () => void;
}

@Component({
  selector: "app-button",
  template: `
    <a class="btn btn-primary" (click)="toolBar.buttonClickValue()">
      My Button
    </a>
  `
})
export class ButtonComponent implements OnInit {
  toolBar: IButton = {
    buttonClickValue: () => this.onCML()
  };

  constructor() {}

  ngOnInit(): void {}

  onCML() {
    alert("Alert should appear on click!!!");
  }
}

Working example: Stackblitz

ruth
  • 29,535
  • 4
  • 30
  • 57