【问题标题】:Why can't I set a select option programmatically when using an object on a Reactive Form in Angular为什么在 Angular 的反应式表单上使用对象时不能以编程方式设置选择选项
【发布时间】:2020-11-19 06:17:25
【问题描述】:

我想弄清楚,因为我无法使用以下打字稿代码设置反应式表单的选择选项:

这是我的课

export class SlotStatusTypes {
    id: number;
    description: string;
}

这是我的组件模板

<select id="subject" formControlName="subject" class="form-control"
   aria-describedby="subject">
   <option *ngFor="let statusType of slotStatusTypesList" [ngValue]="statusType">
      {{statusType.description}}
   </option>
</select>

这在我的组件中:

slotStatusTypesList: SlotStatusTypes[] = [];

slotStatusTypesList 变量由另一个 HTTP GET 调用填充。

在这里我初始化我的表单:

ngOnInit(): void {
   this.slotForm = new FormGroup({
      ...
      subject: new FormControl(null, [
        Validators.required
      ]),
      ...
   });
}

在回调函数内填写slotForm表单,其中主题字段找到对应的值后如下图:

let statusTypeFound: SlotStatusTypes = this.slotStatusTypesList.find(r => r.id === slotPlanning.statusTypeId);

this.slotForm.setValue({
   ...
   subject: statusTypeFound,
   ...
});

到目前为止一切正常。

现在,我想在 slotForm 表单中设置一个相同类型的 SlotStatusTypes 对象,而不是通过列表查找对象,见下文:

let slotStatusType: SlotStatusTypes = {
   id: slotPlanning.id, //id: 1
   description: slotPlanning.description //description: "Available"
};

this.slotForm.setValue({
   ...
   subject: slotStatusType,
   ...
});

此时,slotForm 表单选择没有像我预期的那样使用所选值设置。
为什么在这种情况下它不起作用?

【问题讨论】:

    标签: angular typescript angular-reactive-forms


    【解决方案1】:

    我相信你的问题就在这里,创建新的slotStatusType 对象时。

    let slotStatusType: SlotStatusTypes = {
       id: slotPlanning.id,
       description: slotPlanning.description
    };
    

    它是一个带有新引用的新对象,它不存在于slotStatusTypesList 数组中。所以select 不能将列表中的任何项目与slotStatusType 匹配,尽管属性iddescription 是相同的。

    对于FormControlsetValue,您需要使用slotStatusTypesList 数组中的项目。我不确定您是否可以避免搜索它,但是您可以优化代码以在找到项目后保存对它的引用。

    【讨论】:

    • 嗨 mimo,我解释得更好, slotStatusType 对象只是我需要的自定义对象。我可以尝试传递像 let slotStatusType: SlotStatusTypes = { id: 1, description: "Available" }; 这样的对象,但它无论如何都不起作用。
    • 我明白,您正在尝试做什么,但是每次您通过{...} 创建新对象时,您都是在创建带有新引用的“新鲜”对象。由于您使用数组中的对象初始化下拉列表,select 无法将您的“新鲜”对象引用与其任何选项匹配。
    • 那么,如何在不使用slotStatusTypesList的情况下设置选择输入?
    • 你不能。要在输入中选择项目,您需要使用来自slotStatusTypesList 的项目,因为您分配给输入的值在您的选项中有=== 值。
    • 您可以选择在您的选项中使用[ngValue]="statusType" 来代替[ngValue]="statusType.description"。然后,您将能够以编程方式选择某些内容而无需迭代列表。字符串是原始类型,因此它们不通过引用进行比较。
    猜你喜欢
    • 2020-05-06
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多