我有兩個墊子選擇;您在不同大陸之間選擇的第一個。第二個 mat-select 有國家作為選項。我的問題是,例如,如果我在第一個 mat-select 中選擇亞洲作為我的選項,我只希望亞洲國家在第二個 mat-select 中顯示為選項,而不是其他國家/地區。
<div class="form">
<mat-form-field>
<mat-label>Continents</mat-label>
<mat-select>
<mat-option *ngFor="let continent of formData" [value]="continent.Continent">{{ continent.Continent }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Countries</mat-label>
<mat-select>
<mat-option *ngFor="let country of formData" [value]="country.Countries">{{country.Countries }}</mat-option>
</mat-select>
</mat-form-field>
</div>
這是我在 Typescript 中的 formData
export const formData = [
{
Continent: "Africa",
Countries: [
"Nigeria",
"Egypt",
"Ethiopia"
]
},
{
Continent: "Europe",
Countries: [
"Sweden",
"Italy",
"Hungary"
]
},
{
Continent: "North America",
Countries: [
"United States of America",
"Canada",
"Mexico"
]
},
{
Continent: "South America",
Countries: [
"Peru",
"Argentina",
"Colombia"
]
},
{
Continent: "Asia",
Countries: [
"Malaysia",
"Iran",
"Japan"
]
},
{
Continent: "Australia/Oceania",
Countries: [
"Fiji",
"Australia",
"New Zealand"
]
}
];
uj5u.com熱心網友回復:
我對 Angular 不是很熟悉,但據我所知,您似乎想要檢索<mat-select>. 要做到這一點,最好的辦法是使用從角的雙向系結語法,描述在這里。您還需要更改您的國家/地區選擇器,以便它根據所選大洲過濾結果。
根據上述內容,在您的示例中看起來像這樣:
在您的組件 .html 中:
...
<mat-select [(value)]="selectedContinent">
<mat-option *ngFor="let continent of formData" [value]="continent.Continent">{{ continent.Continent }}</mat-option>
</mat-select>
...
<mat-select>
<mat-option *ngFor="let continent of filteredFormData" [value]="continent .Countries">{{country.Countries }}</mat-option>
</mat-select>
...
在您的組件 .ts 中:
...
selectedContinent?: string;
get filteredFormData() {
// selectedContinent would be undefined if no option is selected
// therefore, we return all of the continents
if (!selectedContinent) return formData;
// filter out all of the continents that don't match the criteria
return formData.filter(entry => entry.Continent === this.selectedContinent);
}
...
或者,您可以使用 將過濾行內到您的第二個選擇器中*ngIf。
uj5u.com熱心網友回復:
為所選條目創建變數(例如selectedContinent)并將其系結在第一個選擇中,然后將其用于在第二個選擇中獲取國家:
<div class="form">
<mat-form-field>
<mat-label>Continents</mat-label>
<mat-select [(ngModel)]="selectedContinent">
<mat-option *ngFor="let continent of formData" [value]="continent">{{ continent.Continent }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Countries</mat-label>
<mat-select>
<mat-option *ngFor="let country of selectedContinent.Countries" [value]="country">{{ country }}</mat-option>
</mat-select>
</mat-form-field>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342745.html
