Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Is one time binding for *ngIf available?

I am creating a DOM structure and only want to add some parts in some visual components at first time and do not want them to be refreshed again and again which is the way *ngIf would work. This is to avoid bindings to execute again and again for things I know will never change once created. In other words, Angular1 has :: operator which help achieve this.

Is there a one time binding for *ngIf available in Angular2? Please point me to the question, if this is discussed in some other question.

like image 991
Abhi Avatar asked Mar 27 '17 13:03

Abhi


1 Answers

You can create your own structural directive which will evaluate passed expression on initial page load and display or not display template in DOM based on value of passed condition, something like this:

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

@Directive({ selector: '[customNgIf]' })
export class CustomNgIfDirective {

    @Input("customNgIf") condition: boolean;

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef) {
    }

    ngOnInit() {
        if (condition) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }
}

You would use it like this:

<div *customNgIf="expression">
    Test
</div>
like image 73
Stefan Svrkota Avatar answered Sep 21 '22 18:09

Stefan Svrkota