动态添加组件ViewContainerRef未定义

时间:2019-03-14 12:05:05

标签: angular

在父Component.ts中

  @ViewChild('dynamic', {
    read: ViewContainerRef
  }) viewContainerRef: ViewContainerRef;

在HTML代码中

<div cdkDropList class="example-container" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let item of testSelector" cdkDrag>
    <div class="title">{{item.key}}</div>
    <div class="content" [innerHTML]="item.value | safeHtml">
    </div>
  </div>
</div>
<ng-template #dynamic></ng-template>

这很好,但是当嵌套在潜水中

<div cdkDropList class="example-container" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let item of testSelector" cdkDrag>
    <div class="title">{{item.key}}</div>
    <div class="content" [innerHTML]="item.value | safeHtml">
       <ng-template #dynamic></ng-template>
    </div>
  </div>
</div>

viewContainerRef是否未定义?

Component.ts

@Component({
 ....
})
export class TestComponent implements OnInit, AfterViewInit {

  @ViewChild('dynamic', {
    read: ViewContainerRef
  }) viewContainerRef: ViewContainerRef;

  constructor(@Inject(Service) private service) {
  }

  ngAfterViewInit() {
    this.service.setRootViewContainerRef(this.viewContainerRef);
    this.service.addDynamicComponent();
  }
}

和service.ts

@Injectable()
export class Service {
    factoryResolver: any;
    rootViewContainer: any;
    constructor(
        @Inject(ComponentFactoryResolver)
        factoryResolver) {
        this.factoryResolver = factoryResolver;
    }
    setRootViewContainerRef(viewContainerRef) {
        this.rootViewContainer = viewContainerRef;
    }
    addDynamicComponent() {
        const factory = this.factoryResolver
            .resolveComponentFactory(JobDashComponent);
        const component = factory
            .create(this.rootViewContainer.parentInjector);
        this.rootViewContainer.insert(component.hostView);
    }
}

1 个答案:

答案 0 :(得分:1)

viewContainerRef是未定义的,因为您用其父标记上的[innerHTML]覆盖了

您可以代替[innerHTML]使用此

<div cdkDropList class="example-container" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let item of testSelector" cdkDrag>
    <div class="title">{{item.key}}</div>
    <div class="content">
       {{item.value | safeHtml}}
       <ng-template #dynamic></ng-template>
    </div>
  </div>
</div>

选择更多具有相同#id的元素:

如果要选择每个具有特定#id的元素,则可以使用QueryList

语法看起来像这样

@ViewChildren('dynamic') viewContainerRefList: QueryList<ViewContainerRef>;

然后,如果对它应用.toArray(),则可以像处理普通数组一样使用它。

const array = viewContainerRefList.toArray();