如何使用angular来重复基于数组列表的按钮(开始/停止)循环


<li *ngFor="let list of lists  "  class="fetch" id="name" >
Name:{{list.name}}  <!-- This Name has the array values ex: j1, j2, j3 -->

<button  style="font-size: 11px;border-radius: 8px;font-weight: bold;background-color: green;" 
*ngIf="isCollapsed" id="name" (click)=" toggleCollapse()"> START</button> 
<button style="font-size: 11px;border-radius: 8px;font-weight: bold;background-color: red;" 
*ngIf="!isCollapsed" id="name" (click)=" toggleCollapse()">STOP</button>
</li>

例如:我有上面给出的数组列表,基于这些列表,我如何为每个项目重复这个开始/停止按钮。

如果我运行此代码,它将显示所有项目的启动/停止按钮,但我的要求是,当单击特定项目(例如:j1(的启动/暂停时,只有j1会启动。

有人能帮我做同样的事吗。

因为看起来所有按钮的id都是name,那不应该也是{{list.name}}吗?这取决于您的toggleCollapse函数。请填写一个最低限度的工作代码示例以获得正确答案。

您只需要在现有的ngFor循环中添加另一个ngFor循环吗?

<li *ngFor="let list of lists  "  class="fetch" id="name" >
Name:{{list.name}}  <!-- This Name has the array values ex: j1, j2, j3 -->
<span *ngFor="let key of list?.name">
<button *ngIf="isCollapsed" (click)="toggleCollapse()">{{key}} START</button> 
<button *ngIf="!isCollapsed" (click)=" toggleCollapse()">{{key}} STOP</button>
</span>
</li>

我并不完全理解这个问题,但与其使用中心标志isCollapsed,不如尝试在lists数组的每个项中包含此标志。然后可以单独设置项目。

控制器

export class AppComponent  {
lists = [
{ name: 'j1', isCollapsed: true },
{ name: 'j2', isCollapsed: true },
{ name: 'j3', isCollapsed: true },
{ name: 'j4', isCollapsed: true }
];
start(name) {
console.log(`started ${name}!`);
}
stop(name) {
console.log(`stopped ${name}!`);
}
}

模板

<li *ngFor="let list of lists" class="fetch" id="name">
Name: {{list.name}}

<button 
style="font-size: 11px;border-radius: 8px;font-weight: bold;background-color: green;" 
id="name" 
(click)="list.isCollapsed = !list.isCollapsed; list.isCollapsed ? stop(list.name) : start(list.name)"
>
{{ list.isCollapsed ? 'START' : 'STOP' }}
</button>
</li>
<pre>{{lists | json}}</pre>

工作示例:Stacklitz

最新更新