Angular 2:如何只在*ngFor的选择性迭代中隐藏按钮



我有以下HTML代码:

<table>
<tr *ngFor='let product of products'>
     <td>
            <button [hidden]="hidebutton" (click)="Follow(product.Id)">Follow</button>                           
     </td>
</tr>
</table>

和相应的点击事件在我的Typescript中如下product.component.ts:

@Component({
   ---
   ---
})
export class followproduct implements onInit{
hidebutton: boolean = false;
Follow(productId: number) {
        ---
        this.hidebutton = true;      
    }
}

当点击一个产品的Follow按钮时,其他迭代产品的所有按钮都被隐藏了——这也是很明显的,因为我将隐藏选项分配给了迭代按钮标签。

是否有任何方法来隐藏,更新或更改按钮的选择迭代*ngFor?

将hidebutton设置为数组。像这样

<table>
    <tr *ngFor='let product of products'>
        <td>
            <button [hidden]="hidebutton[product.Id]" (click)="Follow(product.Id)">Follow</button>                           
        </td>
    </tr>
</table>

在控制器

@Component({
   ---
   ---
})
export class followproduct implements onInit{
hidebutton: any[] = [];
Follow(productId: number) {
        ---
        this.hidebutton[productId] = true;      
    }
}

这是因为所有产品共享相同的变量hidebutton。您需要做的是为每个产品创建一个新变量,如下所示

<tr *ngFor='let product of products'>
     <td>
            <button [hidden]="product.hidebutton"                           
           (click)="Follow(product.Id,product.hiddenbutton)">Follow</button>                           
     </td>
</tr>

export class followproduct implements onInit{
//hidebutton: boolean = false;
Follow(productId: number,hidebutton:boolean) {
        ---
        //if(hidebutton==false)
        hidebutton= true;
        //hidebutton =!hidebutton;    
    }
}

给你的按钮一个id(你应该怎么做),并使用它。

<tr *ngFor='let product of products'>
     <td>
            <button [hidden]="hidebutton==='button'+product.Id" (click)="Follow(product.Id)">Follow</button>                           
     </td>
</tr>

在控制器

@Component({
   ---
   ---
})
export class followproduct implements onInit{
hidebutton: string= '';
Follow(productId: number) {
        ---
        this.hidebutton = 'button'+product.Id;      
    }
}

这样应该可以

对不起,我以前从未使用过Angular2或typescript,所以我不知道语法。可能是这样的

最新更新