【发布时间】:2019-11-15 18:07:25
【问题描述】:
我正在开发一个使用 Angular 8 构建的 SPA,在视图中我有一个表格,我在其中显示来自后端的所有数据并使用 ngFor 循环遍历它。这工作正常。在删除按钮上,我编写了一个逻辑,当用户单击该按钮时,它会向用户显示一条消息 Are you sure you want to delete ,当用户接受时,它会删除该行。
问题是当单击按钮时,所有行都会打开并显示消息。我只希望消息显示在被点击的按钮上,而不是所有按钮上。
Show.component.html
<table class="table table-dark table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Age (Years)</th>
<th>Gender</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of userData">
<td>
{{ user.name}}
</td>
<td>
{{ user.age}}
</td>
<td>
{{ user.gender}}
</td>
<td>
<button class="btn btn-primary" (click)="edit(user.id)">Edit</button>
<span *ngIf="confirmDelete">
<span> Are you sure you want to delete ?</span>
<button class="btn btn-danger" (click)="deleteUser(user.id)">Yes </button>
<button class="btn btn-primary" (click)="confirmDelete=false">No </button>
</span>
<button *ngIf="!confirmDelete" class="btn btn-danger" (click)="confirmDelete=true">Delete</button>
</td>
</tr>
</tbody>
</table>
Show.component.ts
import { Component, OnInit , ViewChild, ElementRef} from '@angular/core';
import { SharedService } from 'src/app/Services/shared.service';
import { AuthService } from 'src/app/Services/auth.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { SnotifyService } from 'ng-snotify';
@Component({
selector: 'app-show',
templateUrl: './show.component.html',
styleUrls: ['./show.component.css']
})
export class ShowComponent implements OnInit {
public userData : any[];
public error = null;
constructor(
private Shared : SharedService,
private Auth:AuthService,
private router: Router,
private Notify:SnotifyService
) { }
ngOnInit() {
this.Shared.checkAll$.subscribe(message => this.userData = message);
}
//delete user
deleteUser(id:number){
return this.Auth.delete(id).subscribe(
data => console.log(data),
error => console.log(error)
);
}
}
【问题讨论】:
标签: angular events button click