我订阅 HTTP 服务器以接收数据,之后我的select
控件将通过 Angular 框架加载数据。我的目标是设置默认值。我的默认值由我从服务器收到的对象的三个值组成,并用“/”分隔,因此 HTML 代码如下所示:
<label>{{ functionStr }}</label>
<select #element formControlName="selectedUser" class="form-select" (change)="changeClient($event)">
<option *ngFor="let account of accountsAvailable4Function">{{ account.firstName }}/{{ account.lastName }}/{{ account.email }}
</option>
</select>
我在初始化时使用了默认值FormGroup
:
var selected = this.accountsAvailable4Function[1].firstName+"/"+this.accountsAvailable4Function[1].lastName+"/"+this.accountsAvailable4Function[1].email
this.form = this.formBuilder.group({
scheduledDate: ['', Validators.required],
selectedUser: [selected, [Validators.required]],
});
这会引发异常,因为我的accountsAvailable4Function
数组尚未初始化。
我尝试使用FormGroup
如下控件来设置它。这也不起作用,因为我怀疑该控件尚未加载:
var selected = this.accountsAvailable4Function[1].firstName+"/"+this.accountsAvailable4Function[1].lastName+"/"+this.accountsAvailable4Function[1].email
this.f['selectedUser'].setValue(selected);
是否有一些我可以监听的事件,以便在加载选择控件时通知我?
附加:加载accountsAvailable4Function
数组:
this.accountService.getAll()
.pipe(first())
.subscribe({
next: (accounts: Account[]) => {
accounts.forEach(account => {
account.userFunctions.forEach(userFunc => {
if(userFunc.userFunction == this.functionStr) {
this.accountsAvailable4Function.push(account);
}
});
});
/* HTML select control selects by default first element - verify it*/
this.selectedAccount = this.accountsAvailable4Function[0];
this.dataSource = new MatTableDataSource(this.accountsSelected4Function);
this.dataSource.paginator = this.paginator;
},
complete: () => {
this.accountsLoaded = true;
var selected = this.accountsAvailable4Function[1].firstName+"/"+this.accountsAvailable4Function[1].lastName+"/"+this.accountsAvailable4Function[1].email
this.f['selectedUser'].setValue(selected);
},
error: error => {
this.alertService.error(error);
this.accountsLoaded = true;
}
});
从当前代码中,您缺少元素
value
的属性<option>
。这导致<option>
元素的值默认为空字符串。因此您会看到该<select>
元素未与默认值绑定。您需要按照as模板表达式
value
所述设置属性。<option>
[]