我期望的结果 创建具有多个选项的角形材料表格。首次访问该页面时。调用了一个api以将数据加载到表单。因此,表单的值应该已经是默认值。 发生了什么 我似乎无法弄清楚为什么我不能为mat-options加载默认选项。
如果不是来自api“耸耸肩”,我可以做到:|
我有一个stalkblitz的链接和下面的一些代码
.html
<form [formGroup]="formGroup" class="col-12">
<div class="row mt-5 justify-content-center align-items-baseline">
<mat-form-field class="col-auto">
<mat-select [compareWith]="compareFn" formControlName="favoriteFood" placeholder="Favorite food">
<mat-option *ngFor="let food of foods$ | async" [value]="food">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<p class="col-auto selected-food"> Selected value: {{formGroup.get('favoriteFood').value | json}} </p>
</div>
</form>
.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import { of } from 'rxjs';
export interface Food {
value: string;
viewValue: string;
}
/**
* @title Basic select
*/
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample implements OnInit {
formGroup:FormGroup;
foods$:Observable<Food[]>;
foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
constructor(private formBuilder:FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
favoriteFood:[this.foods[0].viewValue,[Validators.required]]
});
this.foods$ = of(this.foods);
this.formGroup.get('favoriteFood').patchValue(this.foods[0].viewValue);
}
}
答案 0 :(得分:0)
首先,您不需要使用compareWith
,因为mat-select
支持值的对象,而无需ngValue
或compareWith
。
<mat-select formControlName="favoriteFood" placeholder="Favorite food">
<mat-option *ngFor="let food of foods$ | async" [value]="food">
{{food.viewValue}}
</mat-option>
</mat-select>
第二,您将值设置为对象,因此不仅需要viewValue
,还需要为整个对象设置初始值。我假设您使用patchValue
进行测试。完全不需要。
ngOnInit() {
this.formGroup = this.formBuilder.group({
favoriteFood: [this.foods[0], [Validators.required]]
});
this.foods$ = of(this.foods);
}
答案 1 :(得分:0)
希望对您有帮助。
HTML。
<h4>Basic mat-select</h4>
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<h4>Basic native select</h4>
<mat-form-field>
<mat-label>Cars</mat-label>
<select matNativeControl required>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>
<h4>Usuarios</h4>
<mat-form-field class="col-auto">
<mat-label>Usuarios</mat-label>
<mat-select (selectionChange)="changeClient($event.value)">
<mat-option *ngFor="let user of usuarios$ | async" [value]="user.id">
{{user.title}}
</mat-option>
</mat-select>
</mat-form-field>
TS。
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { Observable } from 'rxjs';
import { of, from } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
export interface Food {
value: string;
viewValue: string;
}
export interface Usuarios {
body: string
id: number
title:string
userId: number
}
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample implements OnInit {
formGroup:FormGroup;
foods$:Observable<Food[]>;
foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
usuarios$:Observable<Usuarios[]>;
selected = '';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
constructor(private formBuilder:FormBuilder, private _http: HttpClient) {}
ngOnInit() {
this.formGroup = this.formBuilder.group({
favoriteFood: [this.foods[0], [Validators.required]]
});
this.foods$ = of(this.foods);
this.usuarios$ = this.getDataUsers();
}
httpClientService(url: string, params: any): Observable<Usuarios[]>{
return this._http.get(url, params).pipe(
map(
(datas) => {
let myTransformedDatas = [];
for(let index in datas){
myTransformedDatas.push(datas[index]);
}
return myTransformedDatas;
}
)
);
}
getDataUsers():Observable<Usuarios[]>{
let urlGetUsuarios = "https://jsonplaceholder.typicode.com/posts";
return this.httpClientService(urlGetUsuarios, {})
}
changeClient(datas){
console.log("selected --->", datas);
this.usuarios$.subscribe(data=>{
console.log("array data",data[datas]);
})
}
}