Angular - 如何从 ngFor 中删除元素
Angular - How To remove the elements from ngFor
我有一个结构如下的数组:
Names : ["X","y","","Z"];
我有一个显示数组元素的 *ngFor 迭代器。我想要那个——忽略数组中的空元素并像这样打印输出:
1. X
2. Y
3. Z
问题出在我使用这段代码时:
<div*ngFor="let child of Names; let bpiIndex = index" class="sub-title _h4">
<span *ngIf="child">{{bpiIndex + 1}}.{{child}}</span>
</div>
它生成如下输出:
1. X
2. Y
4. Z
有没有一种方法可以控制索引,以便它可以省略数组中的 null 或空值(鉴于我正在尝试在模板中执行此操作)?
问题是当您应该实例化一个新变量时,您使用的是实际索引。
let bpiIndex = index
而不是这个 instantiate bpiIndex to 0 并使用 var 所以值保持在循环
var bpiIndex = 0
您还可以缓冲按名称过滤的第二个数组,因此如果值没有名称,它们将不会成为第二个数组的一部分并呈现此新列表。
CurrentArray : string[] = ["X","y","","Z"];
...
ngOnInit() {
this.BufferArrayNoNull = this.CurrentArray.filter(i=>i);
}
this.names = this.names.filter((name)=> {
if(name != '') {
return true
}
}) // ["x", "y", "z"]
所以它会像你预期的那样输出
// 1.X
2.Y
3.Z
获得值后只需 运行 像这样的过滤方法
Names : string[] = ["X","y","","Z"]; // this set the value and the type
...
ngOnInit() {
this.Names = this.Names.filter(i=>i); // falsy value will removed
}
如果您通过 http 请求获得值,请使用 map rxjs 运算符
this.service(...)
.pipe(map( result => result.filter(i=>i)))
.subscribe(result => this.Names = result )
您可以 filter your "Names" list to just hold relevant values. If you need these empty values in the array you has to create the same filter just for output via pipe 或额外过滤的数组并将其仅用于输出。
我有一个结构如下的数组:
Names : ["X","y","","Z"];
我有一个显示数组元素的 *ngFor 迭代器。我想要那个——忽略数组中的空元素并像这样打印输出:
1. X
2. Y
3. Z
问题出在我使用这段代码时:
<div*ngFor="let child of Names; let bpiIndex = index" class="sub-title _h4">
<span *ngIf="child">{{bpiIndex + 1}}.{{child}}</span>
</div>
它生成如下输出:
1. X
2. Y
4. Z
有没有一种方法可以控制索引,以便它可以省略数组中的 null 或空值(鉴于我正在尝试在模板中执行此操作)?
问题是当您应该实例化一个新变量时,您使用的是实际索引。
let bpiIndex = index
而不是这个 instantiate bpiIndex to 0 并使用 var 所以值保持在循环
var bpiIndex = 0
您还可以缓冲按名称过滤的第二个数组,因此如果值没有名称,它们将不会成为第二个数组的一部分并呈现此新列表。
CurrentArray : string[] = ["X","y","","Z"];
...
ngOnInit() {
this.BufferArrayNoNull = this.CurrentArray.filter(i=>i);
}
this.names = this.names.filter((name)=> {
if(name != '') {
return true
}
}) // ["x", "y", "z"]
所以它会像你预期的那样输出
// 1.X
2.Y
3.Z
获得值后只需 运行 像这样的过滤方法
Names : string[] = ["X","y","","Z"]; // this set the value and the type
...
ngOnInit() {
this.Names = this.Names.filter(i=>i); // falsy value will removed
}
如果您通过 http 请求获得值,请使用 map rxjs 运算符
this.service(...)
.pipe(map( result => result.filter(i=>i)))
.subscribe(result => this.Names = result )
您可以 filter your "Names" list to just hold relevant values. If you need these empty values in the array you has to create the same filter just for output via pipe 或额外过滤的数组并将其仅用于输出。