ウェブサイト検索
私は、APIコールからのデータで事前入力したいマルチコンポーネントフォームを持っています。すべてのフィールドには正しくデータが入力されますが、selectタグの選択された値だけが正しく表示されません。valueは正しいのですが、select内の正しいoptionが表示されていません。他の
select
value
option
input
子コンポーネントはフォームグループを受け取り、それがフィールドに入力されるものです。
私は.setValue、.patchValue、[(ngModel)]などを試しましたが、デフォルト値が正しく表示されません。何が間違っているのでしょうか?
.setValue
.patchValue
[(ngModel)]
チャイルドコンポーネント.html
<select [attr.id]="reasonCode" formControlName="reasonCode" placeholder="Reason Code" style="max-width: 100% !important" no-padding selected> <option value="" >Please select reason code</option> <option *ngFor="let reasonCode of reasonCodesService.reasonCodes"> {{reasonCode}} </option> </select>
チャイルドコンポーネント.ts
@Input() newReqForm: FormGroup;
親コンポーネント.html
<div *ngFor="let control of newForm.controls['requisitionItem'].controls; let i = index" style="border: 1px solid black; border-radius: 10px; margin-top: 10px;"> <edit-items (remove)='onRemove($event)' [newReqForm]="newForm.controls.requisitionItem.controls[i]" style="padding-bottom: 10px" [index]='i'></edit-items> </div>
親コンポーネント.ts
ngOnInit() { this.employeeService.loadEmployees(); this.reasonCodesService.loadReasonCodes(); this.itemReqId = +this.route.snapshot.paramMap.get('ReqId'); this.reqService.getRequisition(this.itemReqId).subscribe(response => { this.editReq = response; console.log("EDIT REQ VVV"); console.log(this.editReq); this.editRI = this.editReq.requisitionItem; this.newForm = this.fb.group({ employee: [this.editReq.employee, Validators.required], job: [this.editReq.job, Validators.compose([Validators.pattern("^[0-9]+$")])], requisitionItem: this.fb.array([ ]) }); this.arrayControl = <FormArray>this.newForm.controls['requisitionItem']; this.editRI.forEach(item => { let newItem = this.fb.group({ item: [item.item, Validators.required], quantity: [item.quantity, Validators.compose([Validators.required, Validators.pattern("^[0-9]+$")])], reasonCode: [item.reasonCode], operation: [item.operation], }) this.arrayControl.push(newItem); this.setValidators() }); for (let i = 0; i < this.arrayControl.length; i++) { this.arrayControl.controls[i].get('reasonCode').setValue(this.editRI[i].reasonCode); } this.setValidators(); console.log(this.editReq); this.newReqForm = this.newForm; }); }
私のNode/Angular情報:
Angular CLI: 6.0.8 Node: 8.11.2 OS: win32 x64
編集 child-component.ts
isSelected(reasonCode) { if (reasonCode == this.rc) { return reasonCode } }
選択されたオプションのselectedにバインディングが欠けています(こちらを参照)。リアクティブフォームを使ってselectの値を設定することはできますが、これは実際にオプションを選択することにはなりません。
selected
言い換えると、option に [selected]="isSelected(reasonCode)" のようなものを追加する必要があります。
[selected]="isSelected(reasonCode)"
<option *ngFor="let reasonCode of reasonCodesService.reasonCodes" [selected]="isSelected(reasonCode)"> {{reasonCode}} </option>
例えば、isSelected を実装するには、そのパラメータを FormGroup の参照から取得した値と比較することで行うことができます。
isSelected
FormGroup