LoginSignup
31
30

More than 1 year has passed since last update.

Angular Materialでローディング(処理中)を実装する

Last updated at Posted at 2018-12-27

2022/3/22 追記

@angular/material": "13.2.6" ではこの記事のコードではローディングが表示されない。
原因はこの コミット で MatSpinner クラスが消えたからっぽい。

MatSpinner クラスは消えたが mat-spinner タグは使えるので、自前で MatSpinner コンポーネントを実装して、ComponentPortal に渡すようにする必要がある。

progress-spinner.component.ts
import { Component } from '@angular/core';

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


Angular Materialでローディング(処理中)を実装するには、Progress spinnerOverlayを使う。

まず、Angular Materialをインストールする。

ng add @angular/material

実装はこんな感じ。

app.module.ts
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 { }

app.component.ts
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は特にいじらずにローディングを実装することができる。

31
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
30