简体   繁体   English

Angular 4将值从html模板传递到组件中的方法

[英]Angular 4 passing a value from html template to a method in a component

So I am having this issue on Angular 4. 所以我在Angular 4上遇到了这个问题。

I have this button in my html template markup: 我的html模板标记中有这个按钮:

<td><a class="btn btn-danger" (click)="delete()"><i class="fa fa-trash"></i></a></td>

I have the data assing to each td from a *ngFor, so I have the {{ data.id }} that I can use on this record, but how can I assign it to my delete method correctly, I tried using: 我有来自* ngFor的每个td的数据,所以我有{{data.id}}我可以在此记录上使用,但是如何正确地将它分配给我的删除方法,我尝试使用:

<td><a class="btn btn-danger" (click)="delete({{ data.id }})"><i class="fa fa-trash"></i></a></td>
<td><a class="btn btn-danger" (click)="delete(id)" [id]={{ data.id }}><i class="fa fa-trash"></i></a></td>

But none seem to work, so any advice or guidance would be greatly appreciated. 但似乎没有一个工作,所以任何建议或指导将不胜感激。

just pass data.id to delete function 只需传递data.id即可删除功能

  <td><a class="btn btn-danger" (click)="delete(data.id)"><i class="fa fa-trash"></i></a></td>

and then in your delete function 然后在你的删除功能

    delete(id : any){
console.log(id);
// perform your action
}

You can declare index in your *ngFor like so 您可以在* ngFor中声明索引

  <div *ngFor="let data of items; let i = index">

Then you can use it in your template like so 然后你可以在你的模板中使用它

 <a class="btn btn-danger" (click)="_delete(i)">....</a>

And in your class do something like this 在你的班上做这样的事

public items = [];

public _delete(i) {
   const item = this.items[i];

   //Do what you want with item
}
  • I used "_delete" because "delete" is a reserved word in TypeScript/JavaScript 我使用“_delete”,因为“删除”是TypeScript / JavaScript中的保留字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM