如何在 *ngIf 的 else 部分指向其他组件

diE*_*cho 3 angular-ng-if angular2-template angular

随着我之前的问题的扩展,这里是我需要在其他部分使用模板的另一种情况*ngIf

这是我当前的代码,我在每个页面上使用加载微调器,直到 API 响应返回

   <ng-container *ngIf="!isLoading; else spinner">
         <form [formGroup]="myForm" novalidate (ngSubmit)="submit()" >
            // form content 
         </form>
    </ng-container>
    <ng-template #spinner>
        <div class="fa-3x tc">
            <i class="fas fa-spinner fa-spin"></i>
        </div>
    </ng-template>
Run Code Online (Sandbox Code Playgroud)

这样我们必须在每个页面上编写相同的#spinner组件,所以我创建了一个具有相同内容的组件。

import { Component } from '@angular/core';

@Component({
    selector: 'app-display-loading',
    styles: [`.load__spinner { color: black; text-align: center; font-size: 30px;}`],
    template: `
        <ng-template>
            <div class="load__spinner"> <i class="fas fa-spinner fa-spin"></i></div>
        </ng-template>
    `,
    preserveWhitespaces: true
})

export class DisplayLoadingComponent {
    constructor() {
        console.log('display loading called');
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是如何<app-display-loading>*ngIf 中使用这个组件

或者这可能不是正确的方法。请建议如何做到这一点。

yur*_*zui 5

Angular 结构指令可以帮助我们在 ngIf 指令的 else 部分指向其他组件。

您需要做的就是创建指令来补充内置的 ngIf 指令。

最终语法应如下所示:

<div *ngIf="model withLoading">
  Model
</div>
Run Code Online (Sandbox Code Playgroud)

这只是一种糖:

<ng-template [ngIf]="model" [ngIfWithLoading]="null">
  <div>
      Model
  </div>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

这是指令本身:

@Directive({
  selector: '[ngIfWithLoading]',
})
export class LoadingDirective {
  @Input() set ngIf(val: any) {
    if (!val) {
      const factory = this.resolver.resolveComponentFactory(LoadingComponent);
      this.vcRef.createComponent(factory)
    }
  };

  constructor(private vcRef: ViewContainerRef, private resolver: ComponentFactoryResolver) { }
}
Run Code Online (Sandbox Code Playgroud)

因此,只要模型为假,上面的指令就会放置您的LoadingComponent而不是模型模板。

不要忘记包含LoadingComponententryComponents数组中

吴运行示例

也可以看看