简体   繁体   中英

Angular Material form controls mat-select — mat-option, setting the default option for updating items?

I have a form that has a mat select with mat options and I'm building a reusable component where I can edit any item on the spot. I'm trying to fill in the form default values but after looking for 30 minutes at the documentation and trying various things, I can't seem to set the default selected option in any way.

    <mat-form-field>
        <mat-select [selected]="isSelected()" formControlName="category"  placeholder="Select a category">
          <mat-option *ngFor="let category of videoCategories | async" [value]="category.id">
              {{ category.name }} 
          </mat-option>
        </mat-select>
      </mat-form-field>```

I've tried to use that [selected] but it just errors out as apparently it's not an input property although it does show up in the documentation API here.

I'm thinking this must be possible otherwise it just prevents any form with mat-select to pre-fill for 'updating' functions.

I'm using Angular Material 7 with Angular 7.

EDIT:

My form control code:

this.editVideoForm = new FormGroup({
  title: new FormControl(this.videoTitle, [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
  description: new FormControl(this.videoDescription, [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
  category: new FormControl(this.categoryID, [Validators.required]),
  link: new FormControl("https://vimeo.com/" + this.videoLink, [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
  visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
})

To select a value as default, you need to give your control the desired value.

Here is a stackblitz to show you that : https://stackblitz.com/edit/angular-gqw9yb?file=app/select-multiple-example.ts

export class SelectMultipleExample {
  toppings = new FormControl('Mushroom');
  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}
<mat-select placeholder="Toppings" [formControl]="toppings">
  <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
</mat-select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM