gpt4 book ai didi

Angular Reactive Form 选择选项链接到另一个输入不会改变

转载 作者:行者123 更新时间:2023-12-04 01:02:53 27 4
gpt4 key购买 nike

我想要一个带有从其他输入读取的选项的选择,当输入改变时,我的选择也会改变。

所有选择和输入都是 react 形式。问题是当我更改输入的值时,选择选项仅在我将选项值设置为表单控件时更新。如果我将选项值设置为表单控件的值,它们就不会更新。

示例代码在这里:https://stackblitz.com/edit/angular-5zfocw

模板:

<form [formGroup]="form">
<div formArrayName="opts" *ngFor="let opt of form.get('opts').controls; let i = index">
<div [formGroupName]="i">
{{i}}:
<input type="text" formControlName="name">
</div>
</div>
</form>

<form [formGroup]="form">
<label> Selection:</label>
<select formControlName="selection">
<option *ngFor="let opt of form.get('opts').controls; let i=index" [value]="opt.value.name">
{{opt.value.name}}
</option>
</select>
</form>
<hr>

<pre>
selection: {{ form.get('selection').value | json}}
</pre>

组件:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public form: FormGroup
constructor(private fb: FormBuilder){
this.form = this.fb.group({
opts: this.fb.array([
this.fb.group({name: ['N0']}),
this.fb.group({name: ['N1']}),
this.fb.group({name: ['N2']})
]),
selection: [{value: {}}]
})
}
}

如果我将 HTML 模板中的第 13 行更改为:

<option *ngFor="let opt of form.get('opts').controls; let i=index" [value]="opt">

然后选项和输入就完美同步了。但是,我无法获得选择的值。

如果该行改回 [value]="opt.value.name",然后选择 N2,然后更改 N2 输入,我的选择将丢失并且值不会更新。

我想要什么

我想要 1. 从下拉列表中选择 N2。 2. 在输入中将 N2 更改为其他内容,例如 N22。 3.选择应更新为N22。页面底部应显示值 N22。

我该怎么办?

最佳答案

您需要检查数组何时更改。为此,订阅 this.form.get('opts').valueChanges。使用 pairwise 获取旧值并更改 selection 的值。

在代码中,创建表单后

this.form.get('opts').valueChanges.pipe(
startWith(this.form.value.opts),
pairwise())
.subscribe(([old,value])=>{
const index=old?old.findIndex(x=>x.name==this.form.get('selection').value):-1
if (index>=0)
this.form.get('selection').setValue(value[index].name,{emit:false})
})

stackblitz

更新 如果我们可以删除/添加一些值,数组也会更改。所以如果我们删除一个元素,我们需要考虑。所以,代码变成:

this.form.get('opts').valueChanges.pipe(
startWith(this.form.value.opts),
pairwise())
.subscribe(([old, value]) => {
if (old.length > value.length) { //if we remove some value
//we search if "selection" is in the new value
const index = value? value.findIndex(x => x.name == this.form.get('selection').value) : -1;
if (index == -1) //if not, simple equal to ""
this.form.get('selection').setValue("", { emit: false })
}
else { //Only change the value if we are not removing
const index = old ? old.findIndex(x => x.name == this.form.get('selection').value) : -1
if (index >= 0)
this.form.get('selection').setValue(value[index].name, { emit: false })
}
})

参见 a new stackblitz

关于Angular Reactive Form 选择选项链接到另一个输入不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57882419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com