从Api Service调用angular中选择默认下拉菜单



我试图将从服务调用到数组对象数组的第一个元素获得的对象的下拉列表的默认值设置为。我在这里遵循了各种答案,有选项,如使用比较,但默认值设置看起来在下拉加,当你选择下拉,硬编码的默认值不会消失,但移动到下拉的外部顶部。现在我的代码回到了它的初始状态。下拉菜单正常工作,但最初有一个空白值我希望它具有基于数组

的name元素的第一个对象

手稿
this.brokerageService.getBrokerages().subscribe(brokerage => {
this.brokerageList = brokerage.filter( e => e.name !==  '');
});.......

selectedBrokerageChanged(event: any) {
this.selectedBrokerage = event.value;
}

HTML

<mat-form-field class="mat-form-field">
<mat-select  name="brokerage" id="brokerage"
(selectionChange)="selectedBrokerageChanged($event)">
<mat-option *ngFor="let brokerage of brokerageList " 
[value]="brokerage" >
{{brokerage.name}}
</mat-option>
</mat-select>
</mat-form-field>

从你的评论看来,你试图设置所有选项的第一个值,这是不可能的。您必须在您的mat-option的value中有唯一的对象。

value是触发事件(如selectionChange)时mat-select返回的值。

这里有一个关于Stackblitz的例子,告诉你如何轻松地做到这一点,下面是代码:

ts:

@Component({
selector: "select-value-binding-example",
templateUrl: "select-value-binding-example.html"
})
export class SelectValueBindingExample implements OnInit {
selected = null;
users$: Observable<any>;
constructor(private _http: HttpClient) {}
ngOnInit() {
// this.http.get(...) should obviously go in a service, it's just shorter to show you this way
this.users$ = this._http
.get("https://randomuser.me/api?page=1&results=5&seed=abc")
.pipe(
map((data: any) => data.results),
tap(data => (this.selected = data[0])),
);
}
}

html:

<mat-form-field appearance="fill">
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected">
<mat-option *ngFor="let user of (users$ | async)" [value]="user">{{user.email}}</mat-option>
</mat-select>
</mat-form-field>
<p>You selected: {{selected}}</p>

我使用了一点rxjs来过滤我的数据,并在api调用后设置所选值。

您可能知道,您可以在html部分中看到async管道订阅API调用。pie, map, tap是rxjs的功能,允许你对结果做一些事情。