Angular 7和HTML选择问题

Angular 7和HTML选择问题,angular,angular-reactive-forms,Angular,Angular Reactive Forms,我有一个角度7反应形式,其中包括以下字段: <div class="ui-grid-col-2"> <select formControlName="network_interface" (change)="onInterfaceChange($event.target.value)"> <option *ngFor="let ifc of interfaces; let idx = index;" [value]="ifc.id">

我有一个角度7反应形式,其中包括以下字段:

<div class="ui-grid-col-2">
    <select formControlName="network_interface" (change)="onInterfaceChange($event.target.value)">
        <option *ngFor="let ifc of interfaces; let idx = index;" [value]="ifc.id">
            {{ ifc.id }} - {{ ifc.name }}
        </option>
    </select>
</div>
<div class="ui-grid-col-2">
    <select formControlName="interface_ip">
        <option *ngFor="let obj of interfacesIps; let idx = index;" [value]="obj.id">
            {{ obj.name }}&nbsp;({{obj.address}})
        </option>
    </select>
</div>
这是可行的,每当我更改所选接口时,IP列表都会刷新,但我意识到与组合相关联的表单控件(
interface\u IP
)不会更新。它应该是列表中的第一个IP,但我保留旧值,直到我更改为另一个IP

我已经通过手动更改上面事件处理程序上的表单控件值修复了这个问题,但是我想知道是否有一种方法可以自动完成


提前感谢,

您可以订阅
网络接口
表单控制值更改,如下所示

this.network_interface.valueChanges.subscribe(val => {
// your code here
});

如果您使用的是非字符串值,您可能还需要将
[value]
更改为
[ngValue]
,我认为您需要在选项标记内将
[value]
更改为
[ngValue]

选择标记没有任何值,但选项标记有。因此,如果要在选择标记中绑定选项的值,则需要使用angular的
SelectControlValueAccessor
,它基本上将选项的值绑定到选择标记

您可以通过使用选项标记内的
ngValue
来使用
SelectControlValueAccessor

您需要按以下方式更改代码:

<div class="ui-grid-col-2">
    <select formControlName="network_interface" (change)="onInterfaceChange($event.target.value)">
        <option *ngFor="let ifc of interfaces; let idx = index;" [ngValue]="ifc.id">
            {{ ifc.id }} - {{ ifc.name }}
        </option>
    </select>
</div>
<div class="ui-grid-col-2">
    <select formControlName="interface_ip">
        <option *ngFor="let obj of interfacesIps; let idx = index;" [ngValue]="obj.id">
            {{ obj.name }}&nbsp;({{obj.address}})
        </option>
    </select>
</div>

{{ifc.id}-{{ifc.name}
{{obj.name}}({{obj.address}})

因此,如果您需要一个依赖的下拉列表,您只需要像以前一样用数据填充第一个,要填充第二个,您需要使用一种称为valueChanges的适当的被动形式,它是侦听formControl的更改

this.network_interface.valueChanges.subscribe((selectedValue) => {
    /* 
     Here you select wich data to put in other select based on selectedValue
    */
}); 

谢谢你的建议!这就是我所做的:

我已经更改了
[ngValue]
[value]
。现在,下拉菜单上的
change
事件不再触发,因此我使用网络接口表单控件上的
valueChanges
可观察到的来加载相应的地址:

this.formModel.controls['network_interface'].valueChanges((value) => {
  // Update the addresses on interface change
  this.interfacesIps = this.interfaces[value].ips;
});
现在一切正常


谢谢大家

你能提供一个StackBlitz的例子吗?如果我错了,请纠正我,您是否正在尝试实现依赖下拉列表?嗨!是的,这正是我想要的,一种主从行为,一个下拉列表的值取决于另一个下拉列表的值。当我有时间的时候,我会尝试设置一个Stackblitz演示。我在回答部分写了一个可能的解决方案。
this.formModel.controls['network_interface'].valueChanges((value) => {
  // Update the addresses on interface change
  this.interfacesIps = this.interfaces[value].ips;
});