首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何指向*ngIf的else部分中的其他组件

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

Stack Overflow用户
提问于 2018-10-30 13:06:12
回答 4查看 3.4K关注 0票数 3

对于my previous question的扩展,这里是我需要在*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>

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

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');
    }
}

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-10-31 12:25:37

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

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

最终的语法应该如下所示:

<div *ngIf="model withLoading">
  Model
</div>

这只是一种糖:

<ng-template [ngIf]="model" [ngIfWithLoading]="null">
  <div>
      Model
  </div>
</ng-template>

下面是指令本身:

@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) { }
}

因此,一旦模型为假,上面的指令将放置您的LoadingComponent而不是模型模板。

不要忘记在entryComponents数组中包含LoadingComponent

另请参阅

票数 5
EN

Stack Overflow用户

发布于 2018-10-30 13:48:17

我在整个项目中都使用了类似于<app-display-loading>的东西,我需要做的就是

<app-display-loading *ngIf="isLoading"></app-display-loading>

但首先需要在组件所在的模块中添加DisplayLoadingComponent类,如下所示

exports = [DisplayLoadingComponent]
declarations = [DisplayLoadingComponent]
票数 0
EN

Stack Overflow用户

发布于 2018-10-30 14:35:39

<ng-container *ngIf="!isLoading">
     <form [formGroup]="myForm" novalidate (ngSubmit)="submit()" >
        // form content 
     </form>
</ng-container>

<app-display-loading *ngIf="isLoading"></app-display-loading>

set isLoading accordingly.and,在submit()中设置阻止默认

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53057747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档