问题描述
我使用 angular 9,我有一个复选框列表,默认情况下需要将其设置为 true 以列出一些数据。取消选中这些复选框后,它应该显示某些数据。 我遇到的问题是,当我取消选中并尝试导航到另一个页面时,这些复选框保持未选中状态,这是我不想要的,因为默认情况下,当导航到新页面时,这些复选框需要设置为 true 如何保持默认状态,即在从一个页面导航到另一个页面时始终将复选框列表设置为 true
在我的子组件中
public checkBoxItems: CheckBoxToggleGroupItem[] = [
{ label: 'outofservice',formControl: new FormControl(null) },{ label: 'employment',formControl: new FormControl(null)},];
constructor(private translateService: TranslateService) {
combineLatest(this.checkBoxItems.map(({ formControl }: CheckBoxToggleGroupItem) => formControl.valueChanges))
.pipe(
skipwhile(() => !this.data),takeuntil(this.destroy$)
)
.subscribe(([outOfServiceValue,employmentValue]) => {
this.filterByType(outOfServiceValue,employmentValue);
});
}
public ngOnInit(): void {
this.checkBoxItems.forEach(({ formControl }: CheckBoxToggleGroupItem) => formControl.setValue(true));
this.data$?.pipe(takeuntil(this.destroy$)).subscribe((data: Data) => {
this.data = data?.Report?.ReportPerYears?.reduce(
(accumulator: ReportByTypeAndYear,nextValue: ReportPerYearviewmodel) => ({
...this.groupDataByType(ReportType.Employment,accumulator,nextValue),...this.groupDataByType(ReportType.OutOfService,}),{ [ReportType.Employment]: [],[ReportType.OutOfService]: [] }
);
});
}
感谢您的友好反馈和帮助
解决方法
我建议将您的(控件)复选框放入 FormGroup。
- 您可以将 FromControl 的初始值设置为 true。
- 尝试使用 .patchValue() 而不是 .setValue()
- 如果从代码设置值,则始终调用 .updateValueAndValidity()。
希望我能帮上忙。