はじめに
Angularを使用して、selectboxで複数選択ができるようにする良い感じのフォームを作りたいとなったときに、結構手間取ったので、その手順などをメモしておきます。
方針は、自力で実装するという面倒なことは避けて、そういうことをやってくれるプラグインに任せようという作戦です。
結論
結論として、Angular Materialというライブラリを使用することで実現できることがわかりました。
以下、実装手順になります。
※Angular CLIを使用した手順となりますので、Angular CLIを導入していない方は、以下の記事を参考に導入をお願いします。
https://qiita.com/Yamamoto0525/items/65d5a0b36eb4dbd8079b
手順
1.Angular Materialの導入
コンソールにて、以下のコマンドを実行してください。
ng add @angular/material
するとコンソールに、
Choose a prebuilt theme name, or "custom" for a custom theme:
と出てくるので、好きなテーマを選んでください。
以下、選択肢はすべてy連打で大丈夫です。
Set up HammerJS for gesture recognition? Yes
Set up browser animations for Angular Material? Yes
以上で、Angular Materialの導入は完了です。
2.サンプルアプリの実装
サンプルアプリにはAngular CLIを使用して作成したアプリを使用します。
以下がサンプルアプリから変更を加えたソースです。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSelectModule } from '@angular/material';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatSelectModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
/** @title Select with multiple selection */
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
toppings = new FormControl();
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}
<div class="wrapper">
<mat-form-field>
<mat-select placeholder="Toppings" [formControl]="toppings" multiple>
<mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<router-outlet></router-outlet>
.wrapper {
width: 400px;
height: auto;
margin: 0 auto;
margin-top: 200px;
}
.mat-form-field {
width: 400px;
}
3.サンプルアプリの実行
サンプルアプリの編集が終わったら、アプリを起動していきましょう。
コンソールで以下のコマンドを実行します。
ng serve
アプリが立ち上がったら、ブラウザからアクセスしましょう。
以下のような感じでselectboxが扱えます。
参考
公式のドキュメントです。
https://material.angular.io/components/select/overview
最後に
Jqueryのプラグインは色々見つかりますが、Angularのものは中々見つけられず。
しばらく時間かかってしまったので、この記事が誰かの助けになれば幸いです。