angular - 更改页面后复选框列表保持初始状态
问题描述
我正在使用 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, accumulator, nextValue),
}),
{ [ReportType.Employment]: [], [ReportType.OutOfService]: [] }
);
});
}
感谢您的反馈和帮助
解决方案
我建议将您的(控件)复选框放入 FormGroup。
- 您可以将 FromControl 的初始值设置为 true。
- 尝试使用 .patchValue() 而不是 .setValue()
- 如果从代码设置值,请始终调用 .updateValueAndValidity()。
希望我能帮上忙。
推荐阅读
- python - 如何在 CentOs 中修复“Python 中的 ssl 模块不可用”
- android - 数据绑定 - 未触发自定义对象的 livedata
- php - 使用 mysql 和 php 接待客人和学生
- php - 在 PHP 中合并两个 JSON 数组
- c++ - 在 Bison 和 Flex 中使用变体
- tensorflow - 自定义指标:使用 scikit learn 的 AucRoc Calculator 和 tf.keras
- r - 处理全国的 OSM 数据
- python-3.x - 启动时在 QcomboBox 中显示特定项目
- javascript - 如何将布尔值 true/false 或字符串“true”/“false”列入白名单
- python - 使用 setuptools 将模块安装到站点包