我试图从选择选项中获取一个值以绑定到输入字段,并且该值填充我的反应式表单中的表单属性。这是我的代码:
import 'zone.js/dist/zone';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import {
FormArray,
FormBuilder,
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, FormsModule, ReactiveFormsModule],
templateUrl: 'main.html',
})
export class App {
name = 'Angular';
@ViewChild('templates') templates !: ElementRef
optionChoice: any = '';
taxonomyResponse: any = {
categoryList: [
{
name: 'Option 1',
},
{
name: 'Option 2',
},
{
name: 'Option 3',
},
],
};
form!: FormGroup;
constructor(private fb: FormBuilder) {}
selectForm = this.fb.group({
selectOption: ''
})
onChange() {
this.optionChoice = this.templates.nativeElement.value;
console.log(this.optionChoice)
}
submit() {
console.log(this.selectForm.value);
}
}
bootstrapApplication(App);
这是我的 HTML
<form [formGroup]="selectForm" (ngSubmit)="submit()">
<select id="dropdown" class="form-select" #templates (change)="onChange()">
<option>Please Select Option</option>
<option *ngFor="let t of taxonomyResponse.categoryList">{{t.name}}</option>
</select>
<input type="text" formControlName="selectOption" value="{{optionChoice}}" />
<button type="submit" id="submit">Submit</button>
</form>
我希望能够从所选选项中获取值,将其绑定到输入字段并在我的表单属性上显示该值。我知道我遗漏了一部分,我只是无法弄清楚。
这里是Stack Blitz
的链接谢谢你
您需要将 formControlName 添加到选择中,以便将表单与控件绑定。如果没有 formControlName,Angular 就不知道您的 html 应该是表单的一部分。 将您的 html 更改为:
<select id="dropdown" class="form-select" #templates formControlName="selectOption"
(change)="onChange()">
<option>Please Select Option</option>
<option *ngFor="let t of taxonomyResponse.categoryList">{{t.name}}</option></select>
在这种情况下,您不应该使用
value
属性。
<input type="text" formControlName="selectOptions" />
相反,您应该迭代
FormGroup
FormArray 中的每个 options
并通过 selectOption
方法将值设置为 patchValue
FormControl。
onChange() {
this.optionChoice = this.templates.nativeElement.value;
console.log(this.optionChoice);
for (let i = 0; i < this.options.length; i++) {
(this.options.controls[i] as FormGroup).controls.selectOptions.patchValue(
this.optionChoice,
{ emitEvent: false }
);
}
}