I'm creating a custom *ngIf directive to replace content with a placeholder while it's loading. I have everything working as I want and modeled it after the *ngIf directive (https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_if.ts) The only thing not working is the 'as' syntax and I don't see any references to it or where to start.
*myCustomDirective="loading$ | async as result"
The above does not work, result is undefined when the loading$ observable emits data. The placeholder is shown and replaced with the content as expected however. (Content is giving errors though because of the undefined result)
Import Input, TemplateRef, and ViewContainerRef from @angular/core. To create a custom directive, we need a few elements: Input: This decorator is used to communicate between two components. Here, it allows the data to be input into the directive from the parent component.
A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.
[ngSwitch] is an attribute directive used in combination with *ngSwitchCase and *ngSwitchDefault that are both structural directives. NgSwitch — an attribute directive that changes the behavior of its companion directives.
There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an <ng-container> so that no extra DOM elements are generated.
Updated answer:
You can copy and paste NgIf
directive from Angular github and the only thing you have to do is to change name of NgIfContext#ngIf
to match your custom if directive name, for example:
export class NgIfContext {
public $implicit: any = null;
public appCustomIf: any = null;
}
Then change names of all Input()
respectively to also match your directive name. With this, as
keyword will work. See StackBlitz demo.
EDIT: As a additional reference you can follow these commits in #15025 pull request to see how they implemented as
keyword in NgIf
and NgForOf
. In short:
as
keyword to parser.NgIf
and NgForOf
respectively to use as
syntax.NgForOfContext
,NgIfContext
and made NgForOf
to use NgForOfContext
.Also if you are curious you can see how they implemented let
in NgIf
by following #13297 pull request.
This can help you understand what is going on underneath.
Original answer:
If you don't really care about as
syntax and you only need working template variable this will do the job.
*appCustomIf="test$ | async; let result"
Works with copied and pasted ngIf
from Angular github. See StackBlitz demo.
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