这是一个关于在html元素中同时使用ngFor和NgIf指令的问题的简短教程
- 一个元素上不能有多个模板绑定。在同一个元素上只能使用一个前缀为
- ngFor 和 ngIf在同一个元素上产生错误
ngswitch和ngif在一个html元素中一起使用
根据Angular文档,ngif 和ngfor 指令不能在一个元素中使用。例如,如果这两个指令在一个元素中使用,就会产生错误:Can't have multiple template bindings on one element
在Angular中,一个元素上不能有多个模板绑定的错误。
在这个例子中,我们将在一个元素中使用相同的指令div
让我们创建一个Angular组件
Angular html模板组件
Multiple Directives in Same Elements
Display Table!
{{employee.name}}
import { Component, OnInit } from '@angular/core';
import { Employee } from '../app/employee';
@Component({
selector: 'app-multiple-directive',
templateUrl: './multiple-directive.component.html',
styleUrls: ['./multiple-directive.component.css']
})
export class MultipleDirectiveComponent implements OnInit {
public hide: boolean = false;
showTable() {
this.hide = !this.hide;
}
employees: Employee[] = [
{ id: 1, name: 'Ram', salary: 5000 },
{ id: 2, name: 'John', salary: 1000 },
{ id: 3, name: 'Franc', salary: 3000 },
{ id: 4, name: 'Andrew ', salary: 8000 }
];
constructor() {}
ngOnInit() {}
}
上述组件出现了一个错误
Can’t have multiple template bindings on one element. Use only one attribute prefixed with
原因是Angular不支持在一个元素中使用结构指令
Angular不允许在同一个元素中使用ngIf 和ngFor 指令,如div或li或td或html或自定义元素,解决办法是什么?
如何在Angular中同时使用ngIf和ngFor?
ngIf、ngFor和ngSwitch都是结构化指令,这些指令做主元素和子元素的绑定。当你应用相同的宿主元素时,Angular编译器不能决定哪一个要考虑和优先考虑。
有多种解决方案来处理这个问题
- 使用带有ngIf的父元素,父元素可以是任何DOM元素(div等)或非DOM元素,如
ng-container,然后对子元素使用ngFor。
在这个例子中,创建了一个单独的Div元素,它是带有ngIf指令的父元素。
在Div里面添加了ngFor元素。
<h3>Multiple Directives in Same Elements</h3>
<button (click)="showTable()">Display Table!</button>
<div *ngIf="hide">
<div *ngFor="let employee of employees;">
<span>{{employee.name}}</span>
</div>
</div>
输出

正如你所看到的,增加了一个额外的DOM元素,如果你使用了父子选择器,会破坏CSS样式的变化。它为页面渲染增加了一个额外的DOM元素。
ng-container与ngIf和ngFor一起使用
在这个例子中,ng-container帮助我们将本地html元素分组,它不会增加额外的DOM元素,也不会破坏CSS的变化。
解决方案是
- 使用 元素作为 ngIf 指令的父容器。
- 将ngFor指令元素移到ng-container元素内。
下面是一个例子
<h3>Multiple Directives in Same Elements</h3>
<button (click)="showTable()">Display Table!</button>
<ng-container *ngIf="hide" >
<div *ngFor="let employee of employees;">
<span>{{employee.name}}</span>
</div>
</ng-container>

什么是Angular中的ng-container?
ng-container是一个逻辑容器,用于分组html元素。
- 对DOM元素进行逻辑分组
- 不会在DOM中添加额外的元素
- 可以使用多个ng-container元素
- 输出的HTML将不会产生任何元素
结论
ngSwitch,ngFor在Angular元素中没有与ngIf指令结合。第一个解决方案是用ngIf指令添加父DOM容器html元素,这会导致一个额外的DOM元素节点。 第二个解决方案是使用ng-container,它不会添加额外的DOM元素,这种方法是最好的。