Implementing your own *ngIf

2.6k views Asked by At

I want to create my own *ngIf Directive. The directive will get a number and it wont render the template if the screen inner-Width pixels is less then the number it got.

How can I implement my own *ngIf?

2

There are 2 answers

0
Günter Zöchbauer On BEST ANSWER

It's called structural directive.

You can check the source of *ngIf

There is also a section in the Angular docs about that https://angular.io/guide/structural-directives

The main part is

 this.viewContainer.createEmbeddedView(this.templateRef);

which allows to stamp a template.

If you have

<my-component *myIf="isTrueOrFalse"></my-component>

the * will result in

<my-component></my-component>

being passed as template to the directive, which can then be stamped/removed.

0
eddyP23 On

It is pretty straightforward.

Use the good old ngIf, like this *ngIf='someVariable' and then just toggle this someVariable from true to false when you want it to get rendered or not.

What I would do, is to create an event listener within the component that listens to window width event and looking at the width would decide whether to hide some element or not by setting someVariable