skip to Main Content

I have a button that should call a function fun() . For some reason, the event is not working at all. Here is the code: TS File:

  fun(): void {
    this.test = 'You are my hero!';
    alert('hello')
  }

And the HTML:

<button type="button" (click)="fun()">Click me!</button>

I have no idea what I am doing wrong Please help me.

2

Answers


  1. Try this out,

        import {Component} from '@angular/core';
    
    @Component({
      selector: 'home',
      templateUrl: 'src/home/home.html'
    })
    export class HomeComponent {
      content: string = "";
      count: number = 0;
      
      setMessage1 () {
        this.content = 'This is message # 1';
      }
    }
    

    Button click

    <button (click)="setMessage1()">
    Set Message # 1
    </button>
    
    Login or Signup to reply.
  2. Your code seems to be working fine. If you have trouble working refer the working stackblitz below.

    Check this working code sample:

    Please find the working stackblitz here.

    app.component.ts :

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      test: string;
      count: number = 0;
    
    
      fun(): void {
        this.test = 'You are my hero!';
        this.count++;
        alert('Test message :'+this.test+' Count :'+this.count);
      }
    }
    

    app.component.html:

    <div class="container">
      <button type="button" (click)="fun()">Click me!</button>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search