30秒学会 Angular 片段 · 2020年2月24日

30秒学会 Angular 片段 – Loader Component

You can create own helper component and use it instead of *ngIf.

@Component({
  selector: 'loader',
  template: `
    <ng-content *ngIf="!loading else showLoader"></ng-content>
    <ng-template #showLoader>🕚 Wait 10 seconds!</ng-template>
  `
})
class LoaderComponent {
  @Input() loading: boolean;
}

For usage example:

<loader [loading]="isLoading">🦊 🦄 🐉</loader>

Note that the content will be eagerly evaluated, e.g. in the snippet below destroy-the-world will be created before the loading even starts:

<loader [loading]="isLoading"><destroy-the-world></destroy-the-world></loader>

file:app.component.ts

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

@Component({
  selector: 'loader',
  template: `
    <ng-content *ngIf="!loading else showLoader"></ng-content>
    <ng-template #showLoader>🕚 Wait 10 seconds!</ng-template>
  `
})
export class LoaderComponent {
  @Input() loading: boolean;
}

@Component({
  selector: 'my-app',
  template: `
    <button (click)="isLoading = !isLoading">
      Toggle
    </button>
    <loader [loading]="isLoading">
      🦊 🦄 🐉
    </loader>
  `
})
export class AppComponent {
  isLoading: boolean = true;
}

file:app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent, LoaderComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent, LoaderComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

翻译自:https://www.30secondsofcode.org/angular/s/loader-component

相关链接