0
votes

How do I bind the Google Angular Materials matselection-list with the FormBuilder? We have following class, and trying to use Reactive formBuilder. We know how to bind to the data class with NgModel, but want to bind to the actual formbuilder. What is the process to conduct this with mat-selection-list?

class product{
    productId: number;
    productCode: string;
    productDescription


private formBuilder: FormBuilder,  ) {
    products: this.fb.array([])
}

Also need validation requirements below,

'product': this.formBuilder.group({
  'productId': [null, [Validators.required]],
  'productCode': [null, [Validators.required, Validators.maxLength(50)]],
 'productDescription': [null, [Validators.required, Validators.maxLength(255)]]
})


<mat-selection-list #productList class = "selectionlist" [(ngModel)]="selectedOptions" (selectionChange)="productChangeEvent($event,productList?.selectedOptions.selected)">
    <mat-list-option *ngFor="let product of products">
    {{product.productDescription}}
    </mat-list-option>
</mat-selection-list>

This is a multiple select form.

Was trying to research this, Binding an Angular Material Selection List

1

1 Answers

0
votes

You can refer to the following example. On your .ts file

testForm: FormGroup;
animals: { name: string; sound: string; }[];

constructor(private fb: FormBuilder){
this.testForm = this.fb.group({
  requests: [null]
});
 this.animals = [
  { name: 'Dog', sound: 'Woof!' },
  { name: 'Cat', sound: 'Meow!' },
  { name: 'Cow', sound: 'Moo!' },
  { name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!' },
];
}

On your Html file

<form [formGroup]="testForm">
  <mat-form-field>
    <mat-label>Favorite animal</mat-label>
    <mat-select formControlName="requests" required (ngModelChange)="onChange()">
      <mat-option>--</mat-option>
      <mat-option *ngFor="let animal of animals" [value]="animal">
        {{animal.name}}
      </mat-option>
    </mat-select>
   </mat-form-field>
</form>

Now to check the form field value on your .ts file

 onChange() {
console.log(this.testForm.value.requests);
}

enter image description here