中安拓也のブログ

プログラミングについて書くブログ

Angular Material の Tableを使う

Angular Materialをインストールして、テーブルを表示するところまでやる。

バージョン情報

  • Angular: 5.2.8

  • Angular CLI: 1.7.3

  • Node: 8.9.3

  • angular/cdk: 5.2.4

  • angular/material: 5.2.4

Angular Materialをインストールする

公式サイトの説明に従ってインストールを進めていく。

# Step 1: Install Angular Material and Angular CDK
npm install --save @angular/material @angular/cdk

# Step 2: Animations
npm install --save @angular/animations

# Step 5: Gesture Support
npm install --save hammerjs

@angular/animationshammerjsは、Tableを使用するだけなら必要ないかもしれないが、今後(Angular Materialの)別の部品も導入する予定なのでインストールしておく。

AppModuleの設定

BrowserAnimationsModuleMatTableModuleapp.module.tsimports: []に追加する。

src/app/app.module.ts:

// ...長いので省略
import { QuoinexTickerActions } from '../state/quoinex-ticker/quoinex-ticker.action';
// add this!
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatTableModule } from '@angular/material/table';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    NgReduxModule,
    // add this!
    BrowserAnimationsModule,
    MatTableModule
  ],
// ...長いので省略

// add this!コメントがある部分を追加すればOK

CSSのインポート

Angular MaterialのCSSをstyles.scssにインポートする。

src/styles.scss:

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

ここまでで、Anglar Materialのセットアップは完了🎉🎉🎉

Tableを表示する

HTMLにAngular Materialのテーブルコンポーネントを設置していく

  • HTMLにAngular Materialの<mat-table>コンポーネントを設置することによって、テーブルを表示する

  • [dataSource]インプットにデータ配列をセットすることでテーブルに項目を表示することができる

  • <mat-header-cell>はヘッダーセル、<mat-cell>は各行のデータセルを表す

  • 下のソースコードでは、オブジェクト配列のnamebtcPriceプロパティをデータとしてテーブル上で表示している

src/app/app.component.html:

<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">

    <!-- Exchange Name Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> 取引所 </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>

    <!-- BTC Price Column -->
    <ng-container matColumnDef="btcPrice">
      <mat-header-cell *matHeaderCellDef> BTC価格 </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.btcPrice | number}}円 </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>
  • displayedColumnsにテーブルで表示する列を指定している

  • exchangeList$: Observable<ExchangeModel[]>をsubscribeして、データ配列としてテーブルにセットしている

src/app/app.component.ts:

// ...長いので省略
import { Subscription } from 'rxjs/Subscription';
import { ExchangeModel } from '../state/exchange-list/exchange-list.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  displayedColumns = ['name', 'btcPrice'];
  dataSource: ExchangeModel[];
  subscription: Subscription;

  // ...長いので省略
  @select('exchangeList') readonly exchangeList$: Observable<ExchangeModel[]>;

  constructor(
    private bitflyerService: BitflyerService,
    private coincheckService: CoincheckService,
    private exchangeListService: ExchangeListService,
    private zaifService: ZaifService,
    private bitbankService: BitbankService,
    private quoinexService: QuoinexService
  ) {}

  ngOnInit() {
    // ...長いので省略

    this.exchangeList$
      .filter(value => !!value)
      .filter(value => value.length === 5)
      .subscribe(value => (this.dataSource = value));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

動作確認

データ配列として入力した、各種仮想通貨取引所の名称と現時点でのビットコインの価格がテーブルとして表示されていることがわかる。

f:id:l08084:20180330120230p:plain

参考サイト

Angular Material UI component library