Search code examples
angularangular2-directivesangular-directive

Angular custom ngIf directive 'as' syntax


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)


Solution

  • 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:

    1. In a63d57f they added as keyword to parser.
    2. In 203ee65 and ef93998 they converted NgIf and NgForOf respectively to use as syntax.
    3. Finally in 71d43db they exposed 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.