如何使用插值将值作为参数传入函数?替换removeCompany的32为{{c.id}}
Hey there! Let's tackle your two Angular questions and fix up that code of yours:
1. How do you pass interpolated values as parameters to a function?
First off, a quick Angular template tip: you don't need to use the interpolation syntax ({{ }}) when passing values to functions in event bindings like (click). Interpolation is for rendering values directly into the template (like how you're showing c.name or c.id in the <td>s). When calling a function from an event, you can just reference the variable directly from your context (the c in your *ngFor loop here) as the parameter.
2. Replacing the fixed 32 with c.id in removeCompany
Your original code has a hardcoded 32 and even a broken extra (click)=/> attribute—let's clean that up and pass the dynamic company ID correctly.
Here's your fixed code:
<tr *ngFor="let c of myService.companyList"> <td>{{c.name}}</td> <td>{{c.email}}</td> <td>{{c.password}}</td> <td> <!-- Now passing the dynamic c.id instead of fixed 32 --> <input type="submit" value="click to remove" (click)="removeCompany(c.id)" /> </td> <td> <!-- For the link: add (click) to trigger the function, and prevent default navigation --> <a href="#" (click)="removeCompany(c.id); $event.preventDefault()">Click here to remove this company {{c.id}}</a> </td> </tr>
A couple important points:
- When using
(click)to callremoveCompany, just passc.iddirectly—Angular knows to use the ID of the current company from the*ngForloop, no{{ }}needed here. - I removed that broken
(click)=/>attribute since you only need one(click)binding per element. - For the anchor tag,
$event.preventDefault()stops the browser from trying to navigate to the emptyhref(which would jump to the top of the page), so yourremoveCompanyfunction runs without unwanted side effects.
内容的提问来源于stack exchange,提问作者user10632362

