所以,我有一个列表组件,它在视图模板中有一个子组件。 它使用异步管道与可观察列表循环。 现在我介绍一个搜索控件,它使用它的名称过滤列表并且工作正常 但是当我从控件中删除搜索值时,表单数组会得到重复的控件。
在搜索值时我必须尝试重置表单数组,但没有得到任何结果。
我创建了一个我的实际组件的最小演示组件,只是为了更好地参考我正在做的事情: 这是 sandbox 链接。 重现问题的步骤:
基于
ConfigComponent
,每次(根)输入字段发生变化时,都会将FormGroup
推入FormArray
。这会导致您的 FormArray
值与视图中显示的值不正确。
建议您的
ConfigComponent
应仅处理(单个)config
FormGroup
,而不是处理 FormArray
。
config-list.component.ts 更改:
过滤
config
可观察值的值后,清除现有 pages
FormArray
并与过滤后的数组值绑定。
将
changeDetection: ChangeDetectionStrategy.OnPush
添加到 @Component
装饰器中以防止出现“ExpressionChangedAfterItHasBeenCheckedError”错误。
import {
Observable,
combineLatest,
map,
of,
startWith,
tap
} from 'rxjs';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-config-lists',
templateUrl: './config-lists.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ConfigListsComponent implements OnInit {
ngOnInit(): void {
this.fetchFacebookConfig();
this.setupIntegration();
this.configs = combineLatest([
this.pageAccessTokenConfig,
this.searchConfigControl.valueChanges.pipe(startWith('')),
]).pipe(
map(([configs, searchValue]) => {
return configs.filter((config: any) =>
config.name.toLowerCase().includes(searchValue),
);
}),
tap((configs) => {
(this.integration.controls['pages'] as FormArray).clear();
configs.forEach((x: any) =>
(this.integration.controls['pages'] as FormArray).push(
this.setupPageForm(x),
),
);
}),
);
}
setupPageForm(config: any): FormGroup {
return new FormGroup({
id: new FormControl(config.id || null, {
nonNullable: true,
}),
name: new FormControl(config.name || '', {
nonNullable: true,
validators: [Validators.required],
}),
block_id: new FormControl(config.block_id || '', {
nonNullable: true,
validators: [Validators.required],
}),
});
}
}
config-list.component.html 更改:
具有
formArrayName="pages"
属性的根元素。
将
[formGroupName]="i"
属性添加到 <app-config>
。
删除
[controlGroup]
属性。
<ng-container formArrayName="pages">
<h1 *ngFor="let config of (configs | async); let i = index">{{config.name}}
<app-config
[formGroupName]="i"
[config]="config"
>
</app-config>
</h1>
</ng-container>
config.component.ts 更改:
删除
controlGroup
@Input
变量。
删除将
FormGroup
添加到 FormArray
的逻辑。
export class ConfigComponent implements OnInit {
@Input()
public config!: any;
public pageControl: FormGroup = new FormGroup({});
constructor() {}
ngOnInit(): void {
this.setupForm();
}
/**
* to set up form
* @protected
*/
protected setupForm(): void {
this.pageControl = new FormGroup({
id: new FormControl(this.config.id || null, {
nonNullable: true,
}),
name: new FormControl(this.config.name || '', {
nonNullable: true,
validators: [Validators.required],
}),
block_id: new FormControl(this.config.block_id || '', {
nonNullable: true,
validators: [Validators.required],
}),
});
}
}