如果所选选项的值动态更改,则选择标记值不会更新

时间:2019-07-26 10:00:44

标签: javascript angular

我有四个颜色输入字段(例如Primary,primary2,secondary,secondary2)和一个select标签。选择标签选项值将是这四个输入的值(将有四个选项)。 问题是-如果更改输入值,则选择标签值未更新。如果我手动进行操作,则工作正常。

<div class="color-division"> 
  Primary: <br>
<input type='text' placeholder="Primary Color" [(ngModel)]="primary">
<span class="color-box" [style.background]="primary"></span>
</div>
<div class="color-division"> 
  Primary2:<br>
<input type='text' placeholder="Primary Accent1 Color" [(ngModel)]="primary2">
<span class="color-box" [style.background]="primary2"></span>
</div>
<div class="color-division"> 
  Secondary: <br>
<input type='text' placeholder="Secondary Color" [(ngModel)]="secondary">
<span class="color-box" [style.background]="secondary"></span>
</div>
<div class="color-division"> 
  Secondary2: <br>
<input type='text' placeholder="Secondary Accent 2 Color" [(ngModel)]="secondary2">
<span class="color-box" [style.background]="secondary2"></span>
</div>

<div class="wrapper"> 
<select [(ngModel)]="selectedValue">
  <option [value]="primary"> Primary Color - {{primary}}</option>
  <option [value]="primary2"> primary2 Color - {{primary2}}</option>
  <option [value]="secondary"> secondary Color - {{secondary}}</option>
  <option [value]="secondary2"> secondary2 Color - {{secondary2}}</option>
</select>
<div class="selected-color-box" [style.background]="selectedValue">
  </div>
</div>

enter code here

这是重现问题的stackblitz链接-https://stackblitz.com/edit/angular-v7dkds

1 个答案:

答案 0 :(得分:0)

selectedValue不会在您键入新颜色时更改,因此如果您将primary"blue"修改为"red",并且primary被预先选择, selectedValue仍将包含"blue",因此由于没有匹配项,因此选择为空白。

首先,我将创建一个对象数组,以便我们可以轻松地在循环中显示颜色,然后还可以比较值,因为我们已经引用了同一数组。看起来像这样:

colors = [
  {
    value: 'Primary', color: 'blue'
  },
  {
    value: 'Primary2', color: 'yellow'
  },
  {
    value: 'Secondary', color: 'green'
  }, 
  {
    value: 'Secondary2', color: 'red'
  }
];

selectedValue = this.colors[0];

然后在视图中迭代该数组,将color.color设置为输入的ngModel:

<div class="input-color-division" *ngFor="let color of colors">
  {{color.value}} <br>
  <input [(ngModel)]="color.color" (ngModelChange)="doCompare(color.value)">
  <span class="color-box" [style.background]="color.color"></span>
</div>

与select相同,我们将整个对象用作ngValue,因此使selectedValue成为对象:

<select [(ngModel)]="selectedValue">
  <option *ngFor="let color of colors" [(ngValue)]="color">
    {{color.value}} - {{color.color}}
  </option>
</select>
<div class="selected-color-box" [style.background]="selectedValue.color"></div>

和前面的代码一样,我们添加ngModelChange来监视更改的用户类型。我们比较键入的值是否与selectedValue.value相同,如果是,则从选择中选择该选项,否则不做任何事情:

doCompare(value: string) {
  this.selectedValue.value === value 
    ? this.selectedValue = this.colors.find(x => x.value === value) : null
}

Your forked STACKBLITZ

如果您始终要选择用户输入的颜色,只需将ngModelChange更改为:

(ngModelChange)="selectedValue = color"

STACKBLITZ

或通过在所有选项上添加ngModelChange来修改现有内容:StackBlitz