Angular 5 click bind to anchor tag

Issue

I need to bind a click event on an anchor in my template:

My html looks like this:

<a (click)="deleteUser(user)">
    <i class="la la-trash"></i>
</a>

user is a variable from a previous *ngFor="let user of users"

The deleteUser() function is declared on my users.component.ts file:

import { Component, OnInit, ViewEncapsulation, AfterViewInit } from '@angular/core';
import { Helpers } from '../../../../helpers';
import { ScriptLoaderService } from '../../../../_services/script-loader.service';

import { User } from '../../../../models/user';
import { UsersService } from '../../../../_services/users.service';

import swal from 'sweetalert';


@Component({
    selector: ".m-grid__item.m-grid__item--fluid.m-wrapper",
    templateUrl: "./users.component.html",
    styleUrls: ["./users.component.scss"],
    encapsulation: ViewEncapsulation.None,
})
export class UsersComponent implements OnInit, AfterViewInit {

    users: User[];

    constructor(
        private _script: ScriptLoaderService,
        private usersService: UsersService
    ) { }

    ngOnInit() {
        this.getUsers();
    }

    getUsers(): void {
        this.usersService.getUsers()
            .subscribe(users => this.users = users)
    }

    ngAfterViewInit() {
        this._script.load('.m-grid__item.m-grid__item--fluid.m-wrapper',
            'assets/app/js/users.js');
    }

    deleteUser(user: User): void {
        swal({
            title: `Eliminar usuario ${user.name}`,
            text: "Una vez eliminado, toda su información será eliminada!",
            icon: "warning",
            dangerMode: true,
          })
          .then((willDelete) => {
            if (willDelete) {
                this.usersService.deleteUser(user.id)
                    .subscribe(() => {
                        swal("Usuario eliminado", {
                            icon: "success",
                        });
                    });
            }
          });
    }

}

However that click event is never triggered. It simply doesn’t do anything. No errors, nothing.
I’ve tried a lot of variations to try to make it work:

  • routerLink=””
  • [routerLink]=””
  • href=””
  • href=”#”
  • href=”#!”
  • href=”!#”
  • Change <a> tag for <div>, <span>, <div>, <button> but none worked

I’ve tried this another question but I think it didn’t work because it is Angular2 (I’m using Angular 5).

The template I’m using is Metronic (just in case is relevant)

Solution

i was facing same problem, and find the solution just add class= ‘btn’ its working properlly.

<a class ='btn' ><i (click)="deleteUser(user)" class="la la-trash"></i></a>

Answered By – YOG_PHP

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.