Angular 如何查看表单的值更改并获取表单控件名称?
我有一个方法,它根据select的值过滤数组,并通过与表单控件同名的属性过滤数组Angular 如何查看表单的值更改并获取表单控件名称?,angular,Angular,我有一个方法,它根据select的值过滤数组,并通过与表单控件同名的属性过滤数组 filterLum(val: string | number, c: AbstractControl | string): void { const formGroup = c.parent.controls; const name = Object.keys(formGroup).find((name) => c === formGroup[name]) || null; re
filterLum(val: string | number, c: AbstractControl | string): void {
const formGroup = c.parent.controls;
const name = Object.keys(formGroup).find((name) => c === formGroup[name]) || null;
return this.data.filter(x => x[name] === val);
}
为此,我在每个表单控件中都有一个valueChanges,它可以生成一个过滤器。像这样
this.valueWatcherSubscription = this.form
.get('status')
.valueChanges.pipe(takeUntil(this.unsubscribeSignal.asObservable()))
.subscribe((val) =>
val ? this.filterLum(val, this.form.get('status')) : null
);
问题是我有超过15个表单控件,每一个都有一个观察者。因此,我为所有与数组交互的FormControl创建了一个监视程序。像这样:
const exclude: string[] = ['default'];
const keys = [];
Object.keys(this.form.controls).forEach(key => {
if (exclude.findIndex(q => q === key) === -1) {
keys.push(this.form.get(key).valueChanges);
}
});
const valueWatcherSubscription = merge(...keys);
valueWatcherSubscription.subscribe((val) => console.log(val));
但是这里val只获取select的值,但是我还需要表单的名称,它来自哪里,有没有一种方法可以同时获取form.get('form.control')?这样我就可以在每个控件中使用filterLum函数了
但是这里val只获取select的值,但是我还需要表单的名称,它来自哪里,有没有一种方法也采用form.get('form.control')?这样我就可以在每个控件中使用filterLum函数了
是的,您可以使用表单获取表单控件。控件[键]有几种方法可以实现这一点。与您所拥有的一样,最小的变化是让您的可观察对象返回一个包含两条信息的对象(名称和值),而不仅仅是返回值更改提供的值:
const exclude: string[] = ['default'];
const keys = [];
Object.keys(this.form.controls).forEach(key => {
if (exclude.findIndex(q => q === key) === -1) {
keys.push(this.form.get(key).valueChanges.pipe(
map(val => ({name: key, value: val})) // <------
));
}
});
const valueWatcherSubscription = merge(...keys);
valueWatcherSubscription.subscribe((val) => console.log(val));
最后一种方法是使用from()
:
const exclude: string[] = ['default'];
const controlWatchers = Object.entries(this.form.controls)
.filter(([key]) => !exclude.includes(key))
.map(([name, control]) => control.valueChanges.pipe(
map(value => ({ name, value }))
));
);
const formWatcher$ = merge(...controlWatchers);
formWatcher$.subscribe(console.log);
const exclude: string[] = ['default'];
const formWatcher$ = from(Object.entries(this.form.controls)).pipe(
filter(([key]) => !exclude.includes(key))
mergeMap(([name, control]) => control.valueChanges.pipe(
map(value => ({ name, value }))
));
);
formWatcher$.subscribe(console.log);