File

src/placeholder/placeholder.service.ts

Description

Singleton service used to register the container for out-of-flow components to insert into. Also used to insert/remove components from that view.

Index

Properties
Methods

Methods

createComponent
createComponent(componentFactory: ComponentFactory, injector: Injector)

Creates and returns component in the view.

Parameters :
Name Type Optional Description
componentFactory ComponentFactory<any>
injector Injector
Returns : ComponentRef<any>
destroyComponent
destroyComponent(component: ComponentRef)
Parameters :
Name Type Optional Description
component ComponentRef<any>
Returns : void
hasComponentRef
hasComponentRef(component: ComponentRef)
Parameters :
Name Type Optional Description
component ComponentRef<any>
Returns : boolean
hasPlaceholderRef
hasPlaceholderRef()
Returns : boolean
registerViewContainerRef
registerViewContainerRef(vcRef: ViewContainerRef)

Used by Placeholder to register view-container reference.

Parameters :
Name Type Optional Description
vcRef ViewContainerRef
Returns : void

Properties

Private viewContainerRef
viewContainerRef: ViewContainerRef
Type : ViewContainerRef

Maintain a ViewContainerRef to an instance of the component.

import {
	ComponentRef,
	ViewContainerRef,
	ComponentFactory,
	Injector
} from "@angular/core";
import { Injectable } from "@angular/core";

/**
 * Singleton service used to register the container for out-of-flow components to insert into.
 * Also used to insert/remove components from that view.
 */
@Injectable()
export class PlaceholderService {
	/**
	 * Maintain a `ViewContainerRef` to an instance of the component.
	 */
	private viewContainerRef: ViewContainerRef = null;
	/**
	 * Used by `Placeholder` to register view-container reference.
	 */
	registerViewContainerRef(vcRef: ViewContainerRef): void {
		this.viewContainerRef = vcRef;
	}

	/**
	 * Creates and returns component in the view.
	 */
	createComponent(componentFactory: ComponentFactory<any>, injector: Injector): ComponentRef<any> {
		if (!this.viewContainerRef) {
			console.error("No view container defined! Likely due to a missing `ibm-placeholder`");
		}
		return this.viewContainerRef.createComponent(componentFactory, 0, injector);
	}

	destroyComponent(component: ComponentRef<any>) {
		const index = this.viewContainerRef.indexOf(component.hostView);
		if (index < 0) {
			return;
		}

		// destroy the view
		this.viewContainerRef.remove(index);
	}

	hasComponentRef(component: ComponentRef<any>) {
		if (this.viewContainerRef.indexOf(component.hostView) < 0) {
			return false;
		}
		return true;
	}

	hasPlaceholderRef() {
		return !!this.viewContainerRef;
	}
}

results matching ""

    No results matching ""