2
votes

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

1

1 Answers

3
votes

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