【问题标题】:How do I set the default select value on an array of objects?如何设置对象数组的默认选择值?
【发布时间】:2023-02-09 17:41:53
【问题描述】:

我有一个绑定到对象集合的选择。我想添加一个默认值“请选择”,但我似乎无法让它默认选择该项目:

<select [(ngModel)]="ingredient.definition" class="form-select" name="ingredient{{ i }}">
    <option value="" disabled selected>Please select</option>
    <option *ngFor="let definition of definitions" [ngValue]="definition" [disabled]="disableOption(definition)">{{ definition.name }}</option>
</select>

<button type="button" class="btn btn-primary d-block" [disabled]="disableAdd()" (click)="addIngredient()">Add ingredient</button>

这是我的定义界面:

export interface Definition {
  id: number;
  name: string;
  measurement: string;
  unit: string;
  measurementToUnit: number;
  unitPrice: number;
}

和我的配料界面:

import { Definition } from './definition';

export interface Ingredient {
  quantity: number;
  definition: Definition;
}

select 是动态添加的,所以在添加 select 后我执行以下命令来创建一个空对象:

addIngredient(): void {
    let ingredient: Ingredient = {
      quantity: 0,
      definition: {} as Definition
    }
    this.model.ingredients.push(ingredient);
}

由于我的属性上的定义对象是空的,我希望选择会自动突出显示空的默认选项,但事实并非如此:

我还尝试创建一个名为“请选择”的虚拟 definition 对象并将其添加到 definitions 集合中,但这似乎也不起作用。

有谁知道让这个工作的正确方法?

谢谢

【问题讨论】:

  • 分配 ingredient.definition = "";那应该可以解决您组件中的问题
  • 试试[value]="null" disabled hidden(或[ngValue]="{}" disabled hidden。注意:消除您选择的“已选择”。你正在使用 [(ngModel)],所以你应该只“玩”变量

标签: angular typescript


【解决方案1】:

我遇到过几次这样的场景,因为这个问题是由于动态填充选项的索引而出现的。

尝试使用 formControl 和 patchvalue,而不是 ngModel 和 ngValue。

TS:

public defaultSelectName: string = 'someOption';

public optionsForm: FormGroup = new FormGroup({
    options: new FormControl(null, {validators: Validators.nullValidator})
});

public setDefaultOption(): void {
    const matchedIndex= this.definitions.findIndex(definition => definition.name === defaultSelectName);
    if (matchedIndex) {
        this.optionsForm.get('options')!.patchValue(this. definitions[matchedIndex].name)
    }
}

通过这样做,您明确设置了默认选定值及其索引。

【讨论】:

    【解决方案2】:

    所以根据@Eliseo 的建议,我设法让它与以下项目一起工作:

    <option [value]="{}" disabled>Please select</option>
    

    非常感谢

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2021-06-28
      相关资源
      最近更新 更多