Call a Function on click Event in Angular

In this example, we will create two functions, one is very simple and without any argument call clickFunction() and another we will call dynamic argument with jquery object call callFunction($event, post). one function will call alert and another will only print on console.

Let’s see both example with output as bellow:

app.component.html

<h1>Call a Function on click Event in Angular</h1>
  
<button (click)="clickFunction()">Click Me</button>
  
<div *ngFor="let post of posts">
   <button (click)="callFunction($event, post)">{{ post.title }}</button>   
</div>

app.component.ts

import { Component } from '@angular/core';
   
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'appNgContent';
    
  posts = [
    {
      id: 1,
      title: 'Angular Http Post Request Example'
    },
    {
      id: 2,
      title: 'Angular 8 Routing and Nested Routing Tutorial With Example'
    },
    {
      id: 3,
      title: 'How to Create Custom Validators in Angular 8?'
    },
    {
      id: 4,
      title: 'How to Create New Component in Angular 8?'
    }
  ];
    
  callFunction(event, post){
    console.log(post);
  }
   
  clickFunction() {
    alert("clicked me!");
  }
}
Output:
{id: 2, title: "Angular  Routing and Nested Routing Tutorial With Example"}
0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Spread the love
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x