【发布时间】:2019-09-24 10:17:12
【问题描述】:
我有一个包含多个输入字段的表单(例如:CID、LastName、FirstName 等)。要求是在表单提交时提供一个输入。因此,在任何字段中输入输入时,需要清除输入字段以外的字段中的值
我计划使用 Rxjs 中的一些运算符来组合它并仅使用一个订阅,而不是为所有控件订阅 valuechanges。我发现的是 combineLatest。所以我只是把所有的控件都推到一个数组中,并计划传递给 combineLatest 操作符。
我创建了一个堆栈闪电战。 https://stackblitz.com/edit/angular-xeqms6?file=src%2Fapp%2Fapp.component.ts
handleFormChanges(){
const controlArr=[];
for (const field in this.formControls) {
controlArr.push(this.formEl.get(field).valueChanges);
}
combineLatest(controlArr)
.pipe(map(control=>{
startWith('')
return control;
}))
.subscribe((value)=>{
// Here I need to write the logic to clear input fields other than the current one.
console.log(value);
})
}
上面代码的问题是,只有在所有字段中至少输入一次值后,才会首先触发订阅。后续触发器按预期工作。
我需要的是在每个 valuechanges 订阅回调需要被调用
【问题讨论】:
-
也请分享你的代码链接,你的stackblitz链接没有你写的代码
-
对不起,我的错。这是链接 [链接] (stackblitz.com/edit/…)
-
你为什么不订阅
yourform.valueChanges?不需要逐个字段 -
是的,你是对的,我不知道为什么我没有想到这一点。感谢您的提示