使用Angular Material实现加载(处理中)

2022年3月22日补充

在 “@angular/material”: “13.2.6” 版本中,该文章中的代码无法显示加载状态。
这个问题的原因似乎是由于该提交中的 MatSpinner 类被删除了。

虽然 MatSpinner 类被移除了,但 mat-spinner 标签仍然可用,因此需要自己实现 MatSpinner 组件并传递给 ComponentPortal。

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

@Component({
  selector: 'app-progress-spinner',
  template: '<mat-spinner></mat-spinner>',
})
export class ProgressSpinnerComponent {}


要在Angular Material中实现加载(处理中)的功能,可以使用Progress spinner和Overlay。

首先,安装Angular Material。

 

ng add @angular/material

实现的样子就是这样。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// 追加
import { MatProgressSpinnerModule, MatSpinner } from '@angular/material/progress-spinner';
import { OverlayModule } from '@angular/cdk/overlay';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MatProgressSpinnerModule, // 追加
    OverlayModule             // 追加
  ],
  // 追加
  entryComponents: [
    MatSpinner
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

import { Component, OnInit } from '@angular/core';
import { Overlay } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { MatSpinner } from '@angular/material/progress-spinner';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'sample-progress-spinner';

  overlayRef = this.overlay.create({
    hasBackdrop: true,
    positionStrategy: this.overlay
      .position().global().centerHorizontally().centerVertically()
  });

  constructor(
    private overlay: Overlay
  ) { }

  ngOnInit() {
    // ローディング開始
    this.overlayRef.attach(new ComponentPortal(MatSpinner));
    setTimeout(() => {
      // ローディング終了
      this.overlayRef.detach();
    }, 3000);
  }
}

画面看起来是这样的。

スクリーンショット 2018-12-27 14.20.24.png

只要使用Overlay,就可以在不特別修改HTML的情况下实现加载功能。

bannerAds