0
我正在嘗試使用Angular的反應形式,並且我很難弄清楚如何延遲由服務填充的下拉列表的默認值綁定。下面是我的組件的代碼片段:Angular 2 Reactive Forms,選擇控件從服務中填充
export class TransferComponent {
id: number;
accounts: Account[] = [];
myForm: FormGroup;
transfer: Transfer;
constructor(
private http: Http,
private fb: FormBuilder,
private route: ActivatedRoute,
private transferService: TransferService,
private accountService: AccountService,
private router: Router) {
this.transfer = new Transfer();
this.myForm = fb.group({
'id': [null],
'accountFromId': [this.transfer.accountFromId, Validators.required],
'accountToId': [this.transfer.accountToId, Validators.required],
'title': [this.transfer.title, Validators.required],
'amount': [this.transfer.amount, Validators.required],
'transferDate': [this.transfer.transferDate, Validators.required]
});
}
ngOnInit(): void {
this.accountService.getAccountList()
.then(accounts => this.accounts = accounts);
this.route.queryParams.subscribe(params => {
this.id = params['id'];
if (this.id) {
this.transferService.getTransfer(this.id)
.then(transfer => {
this.transfer = transfer;
this.myForm.setValue(transfer);
});
}
});
}
這裏的想法是嘗試並獲得「ID」參數,傳輸實體呼叫服務,綁定形成與會計分錄預充式下拉菜單。我的部分觀點如下:
<select class="form-control"
id="accountFromInput"
[formControl]="myForm.controls['accountFromId']">
<option *ngFor="let acc of this.accounts" value="{{acc.id}}">{{acc.name}}</option>
</select>
傳輸實體正確大部分域結合,但「accountFromId」選擇元素留下選定的空值(選項是有的,但選擇不正確)。我應該如何重新連線我的組件以確保在從服務獲取帳戶值並將其添加到select後綁定accountFromId?