loadNextToLocation<T extends Object> method

  1. @mustCallSuper
ComponentRef<T> loadNextToLocation<T extends Object>(
  1. ComponentFactory<T> component,
  2. ViewContainerRef location, {
  3. Injector? injector,
})

Creates and loads a new instance of the component defined by component.

The returned ComponentRef is attached next to the provided location in the DOM, similar to how *ngIf and *ngFor operate.

The following API would load a new component next to currentAd:

@Component(
  selector: 'ad-view',
  template: r'''
    This component is sponsored by:
    <template #currentAd></template>
  ''',
)
class AdViewComponent {
  final ComponentLoader _loader;

  @ViewChild('currentAd', read: ViewContainerRef)
  ViewContainerRef currentAd;

  AdViewComponent(this._loader);

  @Input()
  set component(ComponentFactory component) {
    _loader.loadNextToLocation(component, currentAd);
  }
}

May optionally define the parent injector, otherwise defaults to the DI hierarchy that is present where in the view container location.

Implementation

@mustCallSuper
ComponentRef<T> loadNextToLocation<T extends Object>(
  ComponentFactory<T> component,
  ViewContainerRef location, {
  Injector? injector,
}) {
  return location.createComponent(
    component,
    location.length,
    injector ?? location.injector,
  );
}