【问题标题】:Loading Dynamic Components using ngTemplate in ngFor在 ngFor 中使用 ngTemplate 加载动态组件
【发布时间】:2023-03-22 07:35:01
【问题描述】:

我正在尝试设置这样的动态扩展面板:

<mat-accordion>
  <mat-expansion-panel *ngFor="let category of categories">
    <mat-expansion-panel-header>
      <mat-panel-title>
        {{category.name}}
      </mat-panel-title>
    </mat-expansion-panel-header>
    <ng-template #category>
      <a>Test</a>
    </ng-template>
    <mat-action-row>
      <button mat-button color="primary" (click)="nextStep()">Next</button>
    </mat-action-row>
  </mat-expansion-panel>
</mat-accordion>

在我的组件中,我尝试像这样访问每个模板:

@ViewChildren('category') components: QueryList<CategoryDirective>;

ngAfterViewInit() {
    const viewContainerRef = this.adHost;
    if (!_.isUndefined(this.categories) && !_.isUndefined(this.components)) {
      this.components.changes.subscribe(() => {
        this.components.toArray().forEach(el => {
            console.log('ngAfterViewInit', el);
        });
      });
    }
  }

对于每个类别,我都有一个要加载到 ngTemplate 中的组件属性。

我该怎么做?

【问题讨论】:

    标签: angular angular-material angular-directive


    【解决方案1】:

    由于多个“类别”指令,@ViewChild 不起作用。您可以通过为每个项目创建一个单独的组件来解决此问题。

    <mat-accordion>
      <ng-template ngFor let-category [ngForOf]="categories" let-i="index">
        <expansion-panel [title]="category.name" [component]="category.component" [isSelected]="category.isSelected" [index]="i"></expansion-panel>
      </ng-template>
    </mat-accordion>
    

    HTML:


    <mat-expansion-panel [disabled]="!isSelected">
      <mat-expansion-panel-header>
        <mat-panel-title>
          {{title}}
        </mat-panel-title>
      </mat-expansion-panel-header>
      <ng-template category></ng-template>
      <mat-action-row>
        <button mat-button color="primary" (click)="nextStep()">Next</button>
      </mat-action-row>
    </mat-expansion-panel>
    

    并在扩展面板组件中添加以下内容。

    TS:


    @ViewChild(CategoryDirective) categoryDirective: CategoryDirective;
    

    @Input() component: any;
    

    之后你可以动态添加组件:

    ngAfterViewInit(): void {
        if (!_.isUndefined(this.component)) {
          const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.component);
          const viewContainerRef = this.categoryDirective.viewContainerRef;
          console.log(viewContainerRef);
          if (!_.isUndefined(viewContainerRef)) {
            viewContainerRef.clear();
    
            const componentRef = viewContainerRef.createComponent(componentFactory);
            // (<CategoryComponent>componentRef.instance).data = adItem.data;
          }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2016-05-26
      相关资源
      最近更新 更多