对于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>
组件
或者这可能不是正确的方式。请建议如何做到这一点。
发布于 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
另请参阅
发布于 2018-10-30 13:48:17
我在整个项目中都使用了类似于<app-display-loading>
的东西,我需要做的就是
<app-display-loading *ngIf="isLoading"></app-display-loading>
但首先需要在组件所在的模块中添加DisplayLoadingComponent
类,如下所示
exports = [DisplayLoadingComponent]
declarations = [DisplayLoadingComponent]
发布于 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()中设置阻止默认
https://stackoverflow.com/questions/53057747
复制相似问题