Angular 2+ one-time binding

Miquel picture Miquel · Dec 19, 2015 · Viewed 31.6k times · Source

In angular 1 we could do one time binding in this way: {{ ::myFunction() }}.

In angular 2 this is throwing:

EXCEPTION: Template parse errors:
Parser Error: Unexpected token : at column 2 in [{{ ::consent(false, undefined, box) }}] in CookieConsent@5:29 ("ull-right" href="" (click)="consent(true, $event, box)">De acuerdo</a>
        <span class="hidden">[ERROR ->]{{ ::consent(false, undefined, box) }}</span>

How can we do one time binding in angular2?

Answer

m e picture m e · Dec 18, 2017

I found solution for one time binding in angular 2 here: https://github.com/angular/angular/issues/14033

I created this directive:

 import { Directive, TemplateRef, ViewContainerRef, NgZone } from "@angular/core";

@Directive({
    selector: '[oneTime]',
})
export class OneTimeDirective {
    constructor(template: TemplateRef<any>, container: ViewContainerRef, zone: NgZone) {
        zone.runOutsideAngular(() => {
            const view = container.createEmbeddedView(template);
            setTimeout(() => view.detach());
        })
    }
}

And used it:

  <some-selector *oneTime [somePropertyToOneTimeBinding]="someValueToOneTimeBinding"></some-selector>

For example:

     <iframe *oneTime [src]="myUrl"></iframe>