0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Angular】Materialのmat-selectを共通化してみる

Last updated at Posted at 2024-07-28

Angularは好きなんだけど、本音を言うとReactがいいなと思っている泉(@izumin_0401)です。

Angular Materialのプルダウンを共通化したい

ってことで、今回はmat-selectを共通化してみたンゴ。

ブログ記事はこちら

ソースコード

共通mat-selectコンポーネント

pull-down.component.ts
import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';

interface Option {
  name: string;
  value: string;
}

@Component({
  selector: 'app-pull-down',
  standalone: true,
  imports: [CommonModule, MatFormFieldModule, MatSelectModule],
  template: `
    <mat-form-field [style.width]="width">
      <mat-select [(value)]="selected" (selectionChange)="change()">
        <mat-option *ngFor="let option of options" [value]="option.value">{{ option.name }}</mat-option>
      </mat-select>
    </mat-form-field>
  `,
})
export class PullDownComponent {
  @Input() width: string;
  @Input() selected!: string;
  @Input() options!: Option[];
  @Output() event = new EventEmitter<string>();

  change() {
    this.event.emit(this.selected);
  }
}

呼び出し側

app.component.html
<app-pull-down
  [selected]="selectedIndex"
  [options]="[
    { name: '未選択', value: '-1' },
    { name: 'hoge1', value: '0' },
    { name: 'hoge2', value: '1' },
  ]"
  (event)="changePullDown($event)"
></app-pull-down>

もっといい書き方ありそうだけど、一旦これでいいかな...

まとめ

Angular Materialの共通mat-selectコンポーネントを作ってみた。

「@angular/material」のimport箇所を減らせると嬉しくなるよね。

ではまた。

関連記事

最後に

暇つぶしにTwitterブログもやってるので見てね。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?