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:
<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)
Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.
JS code: document. getElementById('mat-checkbox-1-input'). click();
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With