Angular Material 7 - SnackBar



<MatSnackBar>是一個 Angular 指令,用於顯示通知欄,在移動裝置上作為對話方塊/彈出視窗的替代方案。

在本章中,我們將展示使用 Angular Material 顯示 SnackBar 所需的配置。

以下是修改後的模組描述符app.module.ts的內容。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule,MatSnackBarModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatButtonModule,MatSnackBarModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

以下是修改後的 HTML 主機檔案app.component.html的內容。

<button mat-button (click)="openSnackBar('Party', 'act')">Show snack-bar</button>

以下是修改後的 ts 檔案app.component.ts的內容。

import {Component, Injectable} from '@angular/core';
import { MatSnackBar } from "@angular/material";
@Component({
   selector: 'app-root',
   templateUrl: 'app.component.html',
   styleUrls: ['app.component.css']
})
export class AppComponent {
   constructor(public snackBar: MatSnackBar) {}
   openSnackBar(message: string, action: string) {
      this.snackBar.open(message, action, {
         duration: 2000,
      });
   } 
}   

結果

驗證結果。

SnackBar

詳情

  • 在這裡,我們使用 mat-button 建立了一個按鈕,點選該按鈕將顯示 SnackBar。
廣告