【问题标题】:Angular4: Disable button in ngFor after clickAngular4:单击后禁用ngFor中的按钮
【发布时间】:2019-04-16 01:06:47
【问题描述】:

我在 ngFor 循环中有一个 <button>,我希望在用户单击按钮后禁用它。循环的每个元素都有一个按钮,因此我必须为每个元素使用不同的布尔值来区分它们。

这是来自 html 的代码 sn-p:

<div class="card" *ngFor="let i of items">
    <button type="button" [disabled]="'btn' + i.id" (click)="btn + i.id=true">TEST</button>
<div>

[disabled]="'btn' + i.id" 部分似乎有效,但我无法使用(click)="btn + i.id=true" 将其值设置为true。如何连接 btni.id 并将其值设置为 true?

感谢任何帮助!

【问题讨论】:

    标签: angular button ngfor disable


    【解决方案1】:

    头部代码(可能有错误):

    在您的 .ts 组件中使用数组:

    buttons = Array(10).fill(false); // e.g. 10 = size of items
    

    在您的模板中:

    <div class="card" *ngFor="let i of items; index as j">
        <button type="button" [disabled]="buttons[j]" (click)="buttons[j]=true">TEST</button>
    <div>
    

    index as j 适用于 Angular 5/6,较低版本使用 let j=index

    替代解决方案

    添加到禁用的项目字段并直接使用该字段:

    <button type="button" [disabled]="item.disabled" (click)="item.disabled=true">TEST</button>
    

    【讨论】:

    • 谢谢!就像我想要的那样工作。
    【解决方案2】:

    分析下面的代码

    <div class="card" *ngFor="let i of items">
      <button type="button" [disabled]="item.clicked" (click)="item.clicked=true">TEST</button>
    <div>
    

    这就是它应该在 Angular 中实现的方式。

    如果您想知道在您的组件中点击了哪个按钮。然后添加 'clicked' items 数组中的属性,然后在组件中使用它。

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2011-08-19
      相关资源
      最近更新 更多