5

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)

javierojeda
  • 299
  • 1
  • 5
  • 18
  • How do you know it's never fired? I mean how did you debug ? – Vega Mar 15 '18 at 07:47
  • So, I'm assuming your alert didn't show up either? Based on your comment on the other answer I assume you did try to `console.log()` before calling `swal()`. This is indeed strange. Does the console show any errors happening before the (click) event might be registered? Or is your console empty and "clean" without any warnings, errors or anything? Did you debug for example with VSCode and Chrome Debugger? – Agash Thamo. Apr 25 '18 at 09:26
  • This is an old question, but it would be good to know what happened there. @AgashThamo. Yes, the console showed empty and clean. No erros, no warnings, nothing. By that time I didn't know how to use the VSCode debugger. However I used the javascript `debugger` function but it seemed like never get to that function – javierojeda May 01 '18 at 22:04

5 Answers5

8

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>
YOG_PHP
  • 188
  • 1
  • 16
2

I faced same issue where click event on < a > tag was not working.

Work around for that is to wrap < i > tag and put click event on that tag like below

<a href="javascript: void(0)" >
<i class="la la-trash" (click)="deleteUser(user)"></i>
</a>

With this way click event started working but still i had question in my mind why it was not working on < a > tag after some investigation i found it was not working because of below style applied on < a > tag

pointer-events: none;

To fix that issue either remove above style or add below style

pointer-events: all;

Hope this will help if same problem is in your case

Apart from this as a best practice always add href="javascript: void(0)" in < a > tag to avoid it to navigating to home page and style cursor: pointer; if default style of < a > tag is getting over-ridden by some style in your appliction

Vicky Kumar
  • 1,358
  • 1
  • 14
  • 26
  • +1 for this answer, as the other answers call the click event, but the a tag then calls a page refresh. href="javascript: void(0)" is the solution. – Stuart Jun 25 '19 at 13:02
1

I had the same problem. My solution was:

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

When you don't have an < i > tag there you can warp the Link text in < span >

Thomas
  • 1,058
  • 8
  • 15
0

(click) should work for the anchor tags in angular 5. I have tried it. The code seem to be alright to me except the sweet alert ( I don't know what that is).

Try adding a console.log in the start of the method and see if you get that in th elogs

Josf
  • 776
  • 1
  • 8
  • 21
  • Already done that. The `console.log` is not showing neither. At first I thought it has something to do with another function called `deleteUser` but my function is the only one defined in the whole codebase – javierojeda Jan 10 '18 at 21:44
0

What worked for me was to set [routerLink]="['./']" in which case the a tag will beahve as a link but you can bin any additional action to it (e.g (click))

Zvika Badalov
  • 193
  • 2
  • 2
  • 11