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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With