ngfor 嵌套标签 id 根据项目计数递增递减
ngfor nested label id increment decrement according to items count
我有一个标签,其中提到了由 ngFor 添加或删除的项目,我知道我可以放置索引,但索引会继续而无需重置。
喜欢
成员 1
成员2等等。
但是在添加然后删除然后再次添加时,
变成
成员 1
成员 3
我希望该计数自动变为成员 1 和成员 2
请帮忙,我什么都试过了。
添加和删除按钮放置在 ngFor div 之外,这样它们就不会在每次迭代时都被复制。
<div formArrayName="demoArray"
*ngFor="let arrayItem of arrayItems; let i=index">
<div> Member {{ i+1 }} </div>
<input [id]="arrayItem.id" type="checkbox"
[formControl]="demoArray[i]">
<label [for]="arrayItem.id" class="array-item-title">
{{arrayItem.title}}</label>
为获得预期结果,请使用以下选项将修改后的对象数组分配回原始数组,同时删除并在添加时将新对象推送到原始数组
component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
arrayItems = [
{id:1},
{id:2},
{id:3},
]
delete(item){
this.arrayItems = this.arrayItems.filter(v => v.id !== item.id)
}
add(){
this.id++;
this.arrayItems.push({id: this.id})
}
}
示例工作代码供参考 - https://stackblitz.com/edit/angular-lszvvs?file=src/app/app.component.html
已更新 stackblitz,具有相同的功能,但根据 SO 的要求使用了一个添加按钮和一个删除按钮 - https://stackblitz.com/edit/angular-fix4bj?file=src/app/app.component.ts
我有一个标签,其中提到了由 ngFor 添加或删除的项目,我知道我可以放置索引,但索引会继续而无需重置。
喜欢
成员 1
成员2等等。
但是在添加然后删除然后再次添加时,
变成
成员 1
成员 3
我希望该计数自动变为成员 1 和成员 2
请帮忙,我什么都试过了。
添加和删除按钮放置在 ngFor div 之外,这样它们就不会在每次迭代时都被复制。
<div formArrayName="demoArray"
*ngFor="let arrayItem of arrayItems; let i=index">
<div> Member {{ i+1 }} </div>
<input [id]="arrayItem.id" type="checkbox"
[formControl]="demoArray[i]">
<label [for]="arrayItem.id" class="array-item-title">
{{arrayItem.title}}</label>
为获得预期结果,请使用以下选项将修改后的对象数组分配回原始数组,同时删除并在添加时将新对象推送到原始数组
component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
arrayItems = [
{id:1},
{id:2},
{id:3},
]
delete(item){
this.arrayItems = this.arrayItems.filter(v => v.id !== item.id)
}
add(){
this.id++;
this.arrayItems.push({id: this.id})
}
}
示例工作代码供参考 - https://stackblitz.com/edit/angular-lszvvs?file=src/app/app.component.html
已更新 stackblitz,具有相同的功能,但根据 SO 的要求使用了一个添加按钮和一个删除按钮 - https://stackblitz.com/edit/angular-fix4bj?file=src/app/app.component.ts