我正在尝试使用来自远程API服务的值填充材料选择下拉列表。我一直在组件上获取空值或未定义的值。
这是针对使用MEAN堆栈和Angular Material的Angular 7。我尝试了compareWith函数并记录了值。我注意到该组件始终首先加载其值为null,然后再加载具有值的API服务。
<mat-form-field>
<mat-select formControlName="company" placeholder="Select
Company" [(value)]="selectedCompany" [compareWith]="compareFn">
<mat-option *ngFor="let lC of loadedCompanies"
[value]="lC.id">
{{lC.name}}
</mat-option>
</mat-select>
</mat-form-field>
ngOnInit() {
this.authStatusSub = this.authService
.getAuthStatusListener()
.subscribe(authStatus => {
this.isLoading = false;
});
this.form = new FormGroup({
id: new FormControl(null),
company: new FormControl(this.loadedCompanies)
});
this.companyService.getCompanyList();
this.companySub = this.companyService
.getcompanyUpdateListener()
.subscribe((companyData: {companies: Company[]}) => {
this.isLoading = false;
this.loadedCompanies = companyData.companies;
});
}
compareFn(c1: Company, c2: Company): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
我希望值会从可观察对象中加载,并在加载组件之前填充选择输入。
答案 0 :(得分:0)
您可以将*ngIf
添加到父容器中,以便在订阅了Observable并分配了loadedCompanies
之前不会加载mat-select组件。
<mat-form-field *ngIf = "loadedCompanies">
<mat-select formControlName="company" placeholder="Select
Company" [(value)]="selectedCompany" [compareWith]="compareFn">
<mat-option *ngFor="let lC of loadedCompanies"
[value]="lC.id">
{{lC.name}}
</mat-option>
</mat-select>
</mat-form-field>
FormControl公司的初始值应为null,而不是整个loadedCompanies
数组。
this.form = new FormGroup({
id: new FormControl(null),
company: new FormControl(null)
});
这是填充loadedCompanies
数组的方式。
loadedCompanies: Company[];
ngOnInit() {
.
.
// other lines of code before this
this.companyService.getCompanyList().subscribe(companyData => {
this.loadedCompanies = companyData.companies;
});
}