【发布时间】:2022-06-13 23:30:05
【问题描述】:
我目前正在努力以反应形式将所选值动态设置为我的选项之一。 我已经构建了一个编辑模式,如果我打开该编辑模式而不是空白选择,它应该将当前类别显示为选择选项。我的选项在选择时显示良好,但如果我想设置该值,它会以某种方式保持为空(未选中)。
目前我的选择是这样构建的
<select
formControlName="categories"
(change)="selectCategory($event)"
class="form-select"
id="categories">
<option *ngFor="let category of categories"
[value]="category.id">
{{category.name}}
</option>
</select>
我也尝试过像这样构建我的选项
<option *ngFor="let category of categories"
[value]="category.id"
[selected]="category === credential.category">
但这没有用。还尝试检查类别的 .name。
这是我的 .ts 文件的一部分。
public selectCategory(event: Event): void {
const category: Category | undefined = this.categories.find((category: Category) => {
return category.id === parseInt((event.target as HTMLInputElement).value);
});
this.credentialEditForm.get('category')?.setValue(category);
}
// called in the components ngOnInit() method
private initForm(): void {
this.credentialEditForm = this.formBuilder.group({
category: [this.credential.category, Validators.required],
categories: this.categories,
});
}
// called when I open the modal so the current values should be put in
// works on other fields the form has (I just didn't put them in here for the code to be shorter)
private fillFormWithInfo(): void {
this.credentialEditForm.setValue({
category: this.credential.category,
categories: this.credential.category.name,
});
}
我使用类别和类别作为表单字段,因为如果我只使用类别并选择一个选项,则选择字段也不会显示刚刚选择的值。
【问题讨论】:
标签: angular angular-reactive-forms