Search code examples
angulartypescriptcheckboxlistngoninit

List of checkboxs keep initial state after changing page


Am using angular 9 and i have a list of checkboxes that need to be set true by default to list of some data. Upon unchecked of one those checkboxes it should display certain data. The problem i encountered is that when i have unchecked and try to navigate to another page , those checkboxes keep the state of unchecked, which i dont want since by default when navigating to a new page those checkboxes need to set true How to keep the default state, that always set the list of checkboxes to true when navigating from one page to another

In my child component

  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]: [] }
      );
    });
  }

Thank you for kind feedback and help


Solution

  • I'd suggest putting your (controls) checkboxes into a FormGroup.

    • You can set the initial value of the FromControl to true.
    • Try using .patchValue() instead of .setValue()
    • always call .updateValueAndValidity() if setting values from code.

    Hope I could help.