Angular FormControl, patchValue and mat-selection-list

Viewed 625

All I want for now is to have a form w/ a mat-selection-list.

This is the code.

.html

<form [formGroup]="aForm">
 <mat-selection-list #id matInput #idInput formControlName="id" style="width: 20%">
        <mat-list-option #matOption *ngFor="let option of Options" [value]="option"
          (click)="$event.stopPropagation(); changeSelectedOption(matOption.value)" checkboxPosition="before">
          {{ option }}
        </mat-list-option>
      </mat-selection-list>
</form>

.ts

import { Component, OnInit } from '@angular/core';

import { FormBuilder, FormControl, FormGroup, FormGroupDirective } from '@angular/forms';

...

export class AComponent implements OnInit {
aForm: FormGroup;

Options: string[] = ['exclude', 'include', 'excludeDateTtime']

constructor(
    private formBuilder: FormBuilder,
  ) {

    this.aForm = this.formBuilder.group({
      fc: new FormControl({ value: 'exclude', disabled: false }),
    });
   }

  ngOnInit(): void {
  }

  changeSelectedOption(option: any) {

    this.aForm.controls['fc'].patchValue('exclude');
  }

}

Problem 1: initializing formControl

In line fc: new FormControl({ value: 'exclude', disabled: false }), if I provide a value other then '' it throws an error ERROR TypeError: t._value.some is not a function.

Problem 2: updating formControl value

For look & feel reasons I use the mat-selection-list w/ [multiple]="true" and try to override the multiple selections w/ function changeSelectedOption so that, only one option can be picked up in the end.

In line, this.aForm.controls['fc'].patchValue('exclude'); setting the 'exclude' value throws the error ERROR TypeError: t.forEach is not a function.

What do these errors mean? What can I do to solve them?

Thanks.

1 Answers

As is said in some other related questions on StackOverflow, for the formControl.patchValue() to work, the passed argument needs to have the expected data type.

The problematic lines I mention above e.g. fc: new FormControl({ value: 'exclude', disabled: false }), show arguments w/ data type string i.e. 'exclude'.

However, for mat-selection-list the expected data type is Array whether you specify [multiple]="true" or [multiple]="false". I suppose the same holds for all other Angular-Material lists.

Hence the right way, is

fc: new FormControl({ value: ['exclude'], disabled: false }),

and

this.aForm.controls['fc'].patchValue(['exclude']);

Given the opportunity, using '' in fc: new FormControl({ value: '', disabled: false }),

it does not mean the data type is string. Put differently, '' is not the empty string implying thus a string data type. It seems to work more as an any "object" or to denote an object of any type.

Related