【Angular】Mat-autocomplete の使いこなしポイント! 選択オプションのアクセス方法をマスターしよう
このチュートリアルでは、Mat-autocomplete で選択されたオプションにアクセスする方法を、以下のステップに従って説明します。
Mat-autocomplete をセットアップする
まず、Mat-autocomplete コンポーネントをテンプレートに追加する必要があります。
<mat-autocomplete [formControl]="myControl">
<mat-autocomplete-option *ngFor="let option of options" [value]="option.value">
{{ option.label }}
</mat-autocomplete-option>
</mat-autocomplete>
上記の例では、myControl
という名前のフォームコントロールと、options
という名前のオプションリストを使用しています。
選択されたオプションにアクセスするには、selected
イベントを使用します。
this.myControl.selected.subscribe((event) => {
console.log(event.option.value);
});
上記の例では、selected
イベントにサブスクライブし、イベントハンドラーの中で選択されたオプションの値をコンソールに出力しています。
選択されたオプションをフォームコントロールに設定するには、setValue()
メソッドを使用します。
this.myControl.setValue(event.option.value);
上記の例では、setValue()
メソッドを使用して、選択されたオプションの値をフォームコントロールに設定しています。
例
以下の例は、Mat-autocomplete を使用して国を選択するデモです。
<mat-form-field>
<mat-label>国</mat-label>
<mat-autocomplete [formControl]="countryControl">
<mat-autocomplete-option *ngFor="let country of countries" [value]="country.name">
{{ country.name }}
</mat-autocomplete-option>
</mat-autocomplete>
</mat-form-field>
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
countryControl = new FormControl('');
countries = [
{ name: '日本' },
{ name: 'アメリカ合衆国' },
{ name: '中国' },
{ name: 'フランス' },
{ name: 'ドイツ' },
];
constructor() {
this.countryControl.selected.subscribe((event) => {
console.log(event.option.value);
});
}
}
この例では、countries
という名前の配列を使用して、選択可能な国の一覧を定義しています。ユーザーが国を選択すると、その国の名前がコンソールに出力されます。
Mat-autocomplete は、ユーザーがテキストを入力する際に候補リストからオプションを選択できるようにする便利なコンポーネントです。このチュートリアルで説明したように、Mat-autocomplete で選択されたオプションにアクセスするには、selected
イベントと setValue()
メソッドを使用できます。
Angular Mat-autocomplete サンプルコード
HTML (autocomplete.component.html)
<mat-form-field>
<mat-label>国</mat-label>
<input matInput type="text" formControl [matAutocomplete]="auto" placeholder="国を入力">
<mat-autocomplete #auto="matAutocomplete">
<mat-autocomplete-option *ngFor="let country of filteredCountries | async" [value]="country.name">
{{ country.name }}
</mat-autocomplete-option>
</mat-autocomplete>
</mat-form-field>
/* styles for the autocomplete component */
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable, of, Subject } from 'rxjs';
import { map, debounceTime, distinctUntilChanged, filter } from 'rxjs/operators';
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
private _searchTerms = new Subject<string>();
filteredCountries: Observable<string[]>;
countries = [
{ name: '日本' },
{ name: 'アメリカ合衆国' },
{ name: '中国' },
{ name: 'フランス' },
{ name: 'ドイツ' },
];
constructor() {
this.filteredCountries = this._searchTerms.pipe(
debounceTime(300),
distinctUntilChanged(),
filter(term => term.length >= 2),
map(term => this._filterCountries(term))
);
}
private _filterCountries(term: string): string[] {
const filteredCountries = this.countries.filter(country =>
country.name.toLowerCase().includes(term.toLowerCase())
);
return filteredCountries;
}
onSearchChange(event: any) {
this._searchTerms.next(event.target.value);
}
}
このコードでは、以下のことを行っています。
_searchTerms
という Subject を使用して、ユーザーが入力した検索語句を Observable に変換します。filteredCountries
プロパティは、_searchTerms
Observable を subscribe し、検索語句に基づいてフィルタリングされた国のリストを返します。_filterCountries
関数は、検索語句に基づいて国をフィルタリングします。onSearchChange
メソッドは、ユーザーが検索語句を変更するたびに呼び出され、_searchTerms
Subject に新しい値を発行します。
この例は、Mat-autocomplete コンポーネントの基本的な使用方法を示しています。実際には、独自の要件に合わせてコードをカスタマイズする必要があります。
注意事項
このサンプルコードはあくまで一例であり、実際のアプリケーションで使用するにはカスタマイズする必要がある場合があります。
Mat-autocomplete で選択されたオプションにアクセスするその他の方法
matOptionSelected
イベントは、オプションが選択されたときに発生します。このイベントには、選択されたオプションに関する情報が含まれています。
this.myControl.matOptionSelected.subscribe((event) => {
console.log(event.option.value);
});
ViewChild
ディレクティブを使用して、Mat-autocomplete インスタンスにアクセスし、選択されたオプションを取得できます。
@Component({
selector: 'app-autocomplete',
templateUrl: './autocomplete.component.html',
styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent {
@ViewChild('auto') auto: MatAutocomplete;
constructor() { }
getSelectedOption(): string | undefined {
if (this.auto.selected) {
return this.auto.selected.option.value;
} else {
return undefined;
}
}
}
上記の例では、@ViewChild
ディレクティブを使用して auto
変数に Mat-autocomplete インスタンスを格納しています。getSelectedOption
メソッドは、選択されたオプションの値を返します。
ngModel
ディレクティブを使用して、Mat-autocomplete の値をフォームコントロールにバインドできます。
<mat-autocomplete [(ngModel)]="selectedCountry" [formControl]="countryControl">
<mat-autocomplete-option *ngFor="let country of countries" [value]="country.name">
{{ country.name }}
</mat-autocomplete-option>
</mat-autocomplete>
上記の例では、ngModel
ディレクティブを使用して、selectedCountry
変数に選択されたオプションの値をバインドしています。
Template reference variable を使用する
<mat-autocomplete #auto="matAutocomplete">
<mat-autocomplete-option *ngFor="let country of countries" [value]="country.name">
{{ country.name }}
</mat-autocomplete-option>
</mat-autocomplete>
<button (click)="getSelectedOption()">選択されたオプションを取得</button>
getSelectedOption(): string | undefined {
if (this.auto.selected) {
return this.auto.selected.option.value;
} else {
return undefined;
}
}
Mat-autocomplete で選択されたオプションにアクセスするには、さまざまな方法があります。どの方法を使用するかは、個々の要件によって異なります。
注意事項
angular