动态添加组件ViewContainerRef未定义

问题描述 投票:0回答:1

在Parent 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中

<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);
    }
}
angular
1个回答
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();

热门问题
推荐问题
最新问题