10

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.

Abhi
  • 1,624
  • 2
  • 16
  • 29
  • `*ngIf` does not refresh and refresh again if the value doesn't change. And no, there is no one-time binding in Angular2+ – Günter Zöchbauer Mar 27 '17 at 13:26
  • Thanks for your comment. It is my bad, all I meant is optimizing the bindings. – Abhi Apr 03 '17 at 07:36
  • Perhaps you're binding to a method or getter. That's usually not a good idea. Instead call the method or getter from some lifecycle callback or event handler and assign it to a field and bind to that field instead. Change detection works much more efficiently with fields than with methods. – Günter Zöchbauer Apr 03 '17 at 07:37

1 Answers1

1

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>
Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87