0

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 Answers1

0

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

Mridul
  • 1,320
  • 1
  • 5
  • 19
  • For form validations you need to pass validations in this.testForm = this.fb.group({ requests: [null, Validators.required] // like this }); – Mridul Nov 23 '19 at 07:48
  • I suppose data will come from service to bind into drop down so, you should apply required validation preferably for this drop down. you need to specify validations for each form field separately. For multiple validations on one field use Validators.Compose[] – Mridul Nov 23 '19 at 07:55
  • Could you explain more what exactly do you want ? – Mridul Nov 23 '19 at 08:11
  • what you are asking for is not generally followed for binding to a drop down. Since, all such validations are required when we are taking input from a user and validating as per our data base table. – Mridul Nov 23 '19 at 10:47