如何禁用来自ngFor的所有按钮,除了在角度8中单击的按钮



请在浏览器完整 https://stackblitz.com/edit/angular-skzgno?file=src%2Fapp%2Fapp.component.html 中打开它,然后单击任意li标签的按钮/图像,该按钮将更改为不同的图像,就像活动一样。即使您也刷新此活动也不会更改,因为我们正在将 active=true 添加到本地存储中。现在的问题是,当您单击任何 li 的按钮时,在页面加载时,除了该按钮,其他 li 的按钮应该被禁用,当我们刷新时,在您清除本地存储之前也不会有任何变化。请在下面找到代码

app.component.html

<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div>
<pre>
</pre>
<ul>
<li *ngFor="let item of statusdata">
<span>{{item.id}}</span>
<span>{{item.name}}</span>
<button style="margin-left:10px" (click)="toggleActive(item, !item.active)">
<img style="width:50px;margin-left:10px" *ngIf="!item?.active || item?.active === false" src ="https://dummyimage.com/qvga" />
<img style="width:50px;margin-left:10px" style="width:50px;margin-left:10px" *ngIf="item?.active === true" src ="https://dummyimage.com/300.png/09f/fff" />
</button>
</li>
</ul>
</div>

app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
statusdata: any;
ngOnInit() {
this.statusdata = [
{ id: 1, name: "Angular 2" },
{ id: 2, name: "Angular 4" },
{ id: 3, name: "Angular 5" },
{ id: 4, name: "Angular 6" },
{ id: 5, name: "Angular 7" }
];
this.statusdata.forEach(item => {
this.getCacheItemStatus(item);
});
}
toggleActive(item, activeStatus = true) {
if(!this.statusdata.some(d => d.active)){
item.active = activeStatus;
localStorage.setItem(`item:${item.id}`, JSON.stringify(item));
}
}
getCacheItemStatus(item) {
const cachedItem = localStorage.getItem(`item:${item.id}`);
if (cachedItem) {
const parse = JSON.parse(cachedItem); // Parse cached version
item.active = parse.active; // If the cached storage item is active
}
}
}

我很抱歉无法将其适应问题中的代码。我面对这个挑战,不想忘记分享。

假设我们在打字稿文件中有这个;

movies: any[] = [
{ name: 'Wakanda', year: 2010, rating: 4.5 },
{ name: 'Super', year: 2000, rating: 5 },
{ name: 'Deli', year: 2002, rating: 3 },
{ name: 'Fury', year: 2020, rating: 4 },
];
isDisabled: boolean = false;

然后在 HTML 中...

<div *ngFor="let movie of movies;index as i">
<div class="wrapper">
<button (click)="disableBtn('btn' + i)" [disabled]="isDisabled && isDisabled !== 'btn'+i"
id=btn{{i}}>Vote</button>
</div>
</div>

disableBtn函数获取当前按钮并将其分配给isDisabled变量,然后[disabled]属性检查isDisabled是否为真,以及isDisabled是否严格不等于当前按钮。除单击的按钮外,所有其他按钮都是如此。

该函数禁用(切换它(除单击的按钮之外的所有其他按钮。

disableBtn(btn) {
if (this.isDisabled === btn) { //also re-enables all the buttons
this.isDisabled = null;
return;
}
this.isDisabled = btn;
}

你试过[disabled]属性吗?

<button (click)="toggleActive(item, !item.active)" [disabled]="shouldDisable(item)">
shouldDisable(item): boolean {
return !item.active && this.statusdata.some((status) => status.active);
}

最新更新