Button Click In Angular | Solution in 4 Steps

Button Click in Angular
How to handle click event in Angular and

In this example, we will learn how to implement a button click in Angular. We’ll create a simple chores list app with only one component(App Component). It will contain a select element providing a menu of options (all chores) and a button. If the user selects an option and clicks the button, the selected option will be printed on the browser screen in an <ul> element. Therefore, the App Component will collect all selected options in an array. We’ll handle the click event using Event Binding and the basic steps of the application are as follows:

  • The user selects an option from a select element.
  • The user clicks the button.
  • We’ll call a method from the component class.
  • In the method, we’ll keep the selected option of the user in the array property.
  • We’ll print all chores marked(the array) as completed on the page.

Look at the video below to imagine how the app should work:

How our app would work on a button click in Angular

1. Create the app

I’m assuming that you know how to create an app in Angular, so I will give you only a brief overview:

When you run the command ‘ng new buttonclick‘ in the console, Angular will create the root App Component so we don’t need to generate any additional components. We’ll delete the app.component.spec.ts file for simplicity and replace the generated HTML from the template with the following code:

<h1>I am the App Component</h1>
<h2>Select a completed chore</h2>

<!-- We'll add some code here  -->

<h2>List of completed chores</h2>

<!-- We'll add some code here  -->

When you run ng serve in the console, you should see on http://localhost:4200/ a similar result as the shown image:

Output -  Start the app
Output- serving the app

2. Create two properties in app.component.ts and handle the button click in a method

As you can see in the above video, we need to create an array property choresList that will hold each chore. It will represent all choices from which the user can select an option. Therefore, we’ll add a second property to keep each choice of the user: completedChores: string[] = []. So when the button has been clicked, we will push the element into it. Look at the component class:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {

// this represents all options in the select element
  choresList = [
    'Washing dishes',
    'Making the bed',
    'Vaccuming',
    'Dusting',
    'Cleaning the bathroom',
    'Laundry',
    'Watering plants',
    'Grocery Shopping',
    'Cleaning out the oven',
    'Cleaning the windows',
  ];

 // when a user marks a chore as completed, we'll keep the item here
  completedChores: string[] = [];

 // Angular will call this method on click event
 // The method handles the click event

  onCompleteChore(value: string) {
   
    const exists = this.completedChores.find((element) => element === value);
    if (!exists) {
      // we push each selected element into the array 
      this.completedChores.push(value);
    }
  }
}

We’re creating onCompleteChore() method to handle the button click. In it, we’re adding a variable which will show if there is already an existing item with the same value in the completedChores array. The find() function will return undefined, if the value doesn’t exist in completedChores which will show us whether to push the value or not. So the user can’t selects two or more times the same item from the select and the compleredChores won’t contain duplicated elements.

3. Show choresList on the screen, add a button element and handle the button click in Angular

The data(choresList) is hardcoded and we’ll print each item of it using the structural directive *ngFor and string interpolation {{…}} in the HTML template.

<h1>I am the App Component</h1>
<h2>Select a completed chore</h2>

<!-- Here we're creating a template variable #chores-->
<!-- Its value property will give us the selected option (type string)-->
<select #chores>
  <!-- Print each item of the choresList propery -->
  <option *ngFor="let chore of choresList">{{chore}}</option>
</select>

<!--  We're creating a button element and 
      we'are listening for a click event in Angular using parentheses (click);
      Angular will call the onCompleteChore() method when the click event occurs;
      We're passing the value of the selected element to the method and it will be sent to the class
-->
<button type="button" (click)="onCompleteChore(chores.value)">Mark as completed</button>

<h2>List of completed chores</h2>

As shown, we can listen to a click event in Angular enclosing the name of it in parentheses. Keep in mind that we have to omit the prefix ‘on’ in order to work (for example: instead of onClick use click). Angular will call the onCompleteChore method which will handle the click event. The selected value will be sent to the class and we’ll push it to completedChores.

4. Print all chores marked as completed

Add the following code in the end of the component’s template:

<!--Put here the code from the previous snippent-->

<ul>
  <li *ngFor="let completedChore of completedChores; index as i">{{i+1}} - {{completedChore}}</li>
</ul>

The above code will loop trough the completedChores array and it will print each chore marked as completed by the user.

Summary

We created a simple app which helped us to know how to handle a button click in Andular. We learned how to call a specific method from the class when a click event occurs in the browser.

Similar Posts