Angular动态组件渲染问题:如何将组件放入Bootstrap列
解决Angular动态组件Bootstrap列布局堆叠问题
当前动态生成的组件直接堆叠显示,需要将每个动态组件包裹在Bootstrap的col-md-4容器中,实现一行三列的有序排列。以下是具体修改方案:
1. 调整TileRenderComponent模板结构
将ng-template放置在Bootstrap的row容器内,确保列布局的父容器正确:
@Component({ selector: 'app-tile-render', template: `<div class="row"> <ng-template tileHost></ng-template> </div>` })
2. 修改动态组件加载逻辑
在loadComponent方法中,为每个动态组件创建col-md-4容器,并将组件挂载到该容器内:
loadComponent() { this.tiles = this.tileService.getTiles(); const viewContainerRef = this.tileHost.viewContainerRef; viewContainerRef.clear(); for (let i = 0; i < this.tiles.length; i++) { const tileItem = this.tiles[i]; const componentFactory = this.componentFactoryResolver.resolveComponentFactory(tileItem.component); // 创建Bootstrap列容器 const colContainer = this.renderer.createElement('div'); this.renderer.addClass(colContainer, 'col-md-4'); this.renderer.addClass(colContainer, 'mb-3'); // 可选:添加底部间距,优化布局 // 创建动态组件 const componentRef = viewContainerRef.createComponent<TileComponent>(componentFactory); // 传递输入参数 componentRef.instance.itemMasterId = this.itemMasterId; componentRef.instance.partName = this.partName; componentRef.instance.conditionIds = this.conditionIds; componentRef.instance.showViewIcon = this.showViewIcon; // 将组件挂载到列容器中 this.renderer.appendChild(colContainer, componentRef.location.nativeElement); // 将列容器添加到row中 this.renderer.appendChild(viewContainerRef.element.nativeElement, colContainer); } }
3. 优化父组件结构
父组件中无需额外嵌套row,避免布局层级冲突:
<div class="container-fluid p-0"> <app-tile-render #tileRender [itemMasterId]="itemMasterId" [partName]="partName" [conditionIds]="conditionIds" [showViewIcon]="true"></app-tile-render> </div>
修改完成后,每个动态组件都会被col-md-4容器包裹,自动遵循Bootstrap栅格系统规则:中等及以上屏幕一行显示3个组件,小屏幕自动堆叠,解决组件堆叠的问题。
内容的提问来源于stack exchange,提问作者Vishal Suthar
相关产品推荐
相关产品推荐

