【问题标题】:How do I render a component inside another dynamically loaded component in Angular?如何在 Angular 中另一个动态加载的组件中渲染组件?
【发布时间】:2020-11-23 04:14:35
【问题描述】:

我正在尝试制作一个自定义 Grid 组件,我想在其中呈现/传递其他组件。我创建了一个 Grid 组件,并在我的dashboard.component.ts 中动态加载它。

这是我的网格模板。

<div nz-row *ngFor="let row of grid; index as i;">
    <div nz-col *ngFor="let col of row; index as j;">
      <div>
        <ng-template name="{{i}}{{j}}"></ng-template>
      </div>
    </div>
</div>

指令。

@Directive({
  selector: 'ng-template[name]'
})
export class CustomGridDirective {
  @Input() name: string;

  constructor(public viewContainerRef: ViewContainerRef) { }
}

我的custom-grid.component.ts,

export class CustomGridComponent implements OnInit {

  @Input() grid: any;
  @ViewChildren(CustomGridDirective) gridContainer: QueryList<CustomGridDirective>;
  
  constructor() {}
  
  ngOnInit() {
  }
}

Dashboard.component.ts,我在这里动态加载我的 Grid 组件。

async customGrid(){
  const {CustomGridComponent} = await import('../custom-grid/custom-grid.component');
  const customGridFactory = this.cfr.resolveComponentFactory(CustomGridComponent);
  let {instance} = this.anchor1.createComponent(customGridFactory, null, this.injector);
  instance.grid = [
    ['1', '2', '3']
  ]
  return instance
}

ngAfterViewInit() {
  this.customGrid().then( component => console.log(component.gridContainer));
}

现在,我无法访问 component.gridContainer 甚至 component.grid。两者都返回,undefined。

假设我有一个dashboard-widget-1.component,如何在自定义网格组件中动态呈现它?我试图接近 ViewChildren 的查询列表并尝试在其中呈现组件。

但我得到component.gridContainer 和component.grid,两者都是未定义的。如何在我的网格组件(我已动态加载)中动态呈现组件,例如dashboard-widget-1.component 和dashboard-widget-2.component?

我被困了好几天,任何帮助将不胜感激。

【问题讨论】:

  • 你准备好 stackblitz 了吗?
  • 你好尤里,这是我的 StackBlitz。 stackblitz.com/edit/angular-ivy-4akuyg。我想在屏幕中显示的 00、01、02 等中渲染/插入模板。谢谢,请帮忙。

标签: angular


【解决方案1】:

它是undefined,因为尚未在该组件上执行任何更改检测周期。

componentRef.changeDetectorRef.detectChanges();

const widgetFactory = this.cfr.resolveComponentFactory(CustomWidgetComponent);
instance.galleryContainer.forEach(target => {
  target.viewContainerRef.createComponent(widgetFactory, null, this.injector)
});

此外,如果您想延迟加载组件,请确保导入的文件包含描述所有相关声明的 NgModule:

custom-grid.components.ts

@Component({
  ...
})
export class CustomGridComponent implements OnInit {
  ...
}
... 
@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [CustomGridComponent, CustomGridDirective],
})
export class CustomGridModule { }

Forked Stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-29
    • 2021-12-04
    • 2020-09-04
    • 2018-08-13
    • 2019-10-14
    • 2017-10-07
    • 2023-02-10
    • 2021-01-12
    相关资源
    最近更新 更多