Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Mat Select Trigger with FormControl

Tags:

angular

Angular material select dropdown with mat select trigger.

Trying to create select dropdown like this :

https://stackblitz.com/angular/omvmgjjbnnq?file=app%2Fselect-custom-trigger-example.ts

My Code :

component.ts


export class SelectCustomTriggerExample implements OnInit {
  dispForm : FormGroup
  constructor(private fb : FormBuilder) {}
  ngOnInit() {
    this.dispForm = this.fb.group({
        toppings : ['']
     })
  }


  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}

component.html

<mat-form-field>
  <form [formGroup]="dispForm">
  <mat-select placeholder="Toppings" formControlName="toppings" multiple>
    <mat-select-trigger>
      {{toppings.value ? toppings.value[0] : ''}}
      <span *ngIf="toppings.value?.length > 1" class="example-additional-selection">
        (+{{toppings.value.length - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
      </span>
    </mat-select-trigger>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
  </form>
</mat-form-field>

I have changed formControl to formControlName and code stopped working

like image 600
Shivaay Avatar asked Jan 02 '26 03:01

Shivaay


1 Answers

Your code defines two form controls. When using [formControl], you're using only one of them: the one created using toppings = new FormControl();.

When using formControlName, you're using both: the one created using toppings : [''] is the one bound to your select, and the other one is the one used by your trigger.

There should be only one form control. And all the code should use that using form control.

Replace, in your component,

toppings = new FormControl();

by

get toppings(): FormControl {
  return this.dispForm.get('toppings') as FormControl;
}

Also, your form is named dispForm, not dispform. And it must be formControlName="toppings", not [formControlName]="toppings".

Demo

like image 167
JB Nizet Avatar answered Jan 04 '26 22:01

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!