Walter White
Walter White

Reputation: 1024

Adding component dynamically ViewContainerRef is undefined

In Parent Component.ts

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

In HTML code

<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>

This work fine but when nested inside dive

<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 is undefined?

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();
  }
}

and 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);
    }
}

Upvotes: 0

Views: 1288

Answers (1)

joka00
joka00

Reputation: 2557

The viewContainerRef is undefined because you overwrite it with the [innerHTML] on it's parent tag

Instead of [innerHTML] you can use this

<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>

Select more elements with same #id:

If you want to select every element with a specific #id then you can use QueryList.

The syntax would look like this

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

Then you can then work with it like with normal array if you apply .toArray() on it.

const array = viewContainerRefList.toArray();

Upvotes: 2

Related Questions