Gerald Gonzales
Gerald Gonzales

Reputation: 533

Is it possible to disable the element created by ViewContainerRef

I have implemented a directive which decides whether it will render an element or not.

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

export class MyDirective {

    constructor(private _templateRef: TemplateRef<any>,
        private _viewContainer: ViewContainerRef) {
    }

    @Input() set method() {
        this._viewContainer.clear();
        if (// some logic here //) {
            this._viewContainer.createEmbeddedView(this._templateRef) // render element
        }
}

My problem now is I want to render the element but I also need to decide whether it is enabled or not. Is there a way to do this within the directive itself?

Upvotes: 0

Views: 1279

Answers (2)

M.Laida
M.Laida

Reputation: 1938

It is not possible, maybe should try to display a dummy component, if you do not want to clear (this._viewContainer.clear()) it.

  @Input() set method() {
    this._viewContainer.clear();
    if (// some logic here //) {
        this._viewContainer.createEmbeddedView(this._templateRef) // render element
    } else {
        const factory = this.resolver.resolveComponentFactory(DummyComponent);
        this.viewContainer.createComponent(factory);
    }
  }
  • DummyComponent - Create a dummyComponent you want to display

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222750

It can be done the same way it is done in built-in ngIf directive:

if (// some logic here //) {
    this._viewContainer.createEmbeddedView(this._templateRef) // render element
} else {
    this._viewContainer.clear();
}

Upvotes: 1

Related Questions