Angular中如何将ngFor当前项传递给组件@Input()且无需额外父组件
你现在的写法本身就不需要额外包裹父组件,是完全可用的。
*ngFor 作为Angular内置的结构性指令,支持直接绑定在你需要循环渲染的自定义组件上,不需要额外套一层<div>或其他容器元素。你原代码只需要修正语法错误([item]绑定的属性值缺了闭合双引号)就可以直接运行:
<my-component *ngFor="let currentItem of items" [item]="currentItem"></my-component>
如果你需要在循环内渲染多个平级元素,又不想额外生成多余的DOM父节点,可以用无渲染的<ng-container>作为*ngFor的宿主,它不会在最终DOM树中生成真实节点,完全不会影响布局:
<ng-container *ngFor="let currentItem of items"> <my-component [item]="currentItem"></my-component> <!-- 可放置其他平级元素,不会额外嵌套父节点 --> <p *ngIf="currentItem.desc">{{ currentItem.desc }}</p> </ng-container>
内容的提问来源于stack exchange,提问作者nandesuka
相关产品推荐
相关产品推荐

