首页 > 解决方案 > 更改页面后复选框列表保持初始状态

问题描述

我正在使用 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]: [] }
      );
    });
  }

感谢您的反馈和帮助

标签: angulartypescriptcheckboxlistngoninit

解决方案


我建议将您的(控件)复选框放入 FormGroup。

  • 您可以将 FromControl 的初始值设置为 true。
  • 尝试使用 .patchValue() 而不是 .setValue()
  • 如果从代码设置值,请始终调用 .updateValueAndValidity()。

希望我能帮上忙。


推荐阅读