You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用插值将值作为参数传入函数?替换removeCompany的32为{{c.id}}

Angular: Passing Dynamic Values to Template Functions

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 call removeCompany, just pass c.id directly—Angular knows to use the ID of the current company from the *ngFor loop, 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 empty href (which would jump to the top of the page), so your removeCompany function runs without unwanted side effects.

内容的提问来源于stack exchange,提问作者user10632362

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:10:33