Rattus
Rattus

Reputation: 105

Angular / FormBuilder Set default value for mat-select dropdown

I am trying to set a default value for a dropdown in my project. I've tried several different ways of doing this, but nothing I've tried seems to work. I have tried setting the default using the [(value)] inside the mat-select and by using the .setValue(...) function on the formBuidler. I have replicated the structure of my code in a stackblitz. Does anyone know what I am missing or why what I currently have does not work? Any help is appreciated

Upvotes: 0

Views: 515

Answers (2)

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

I could see 2 problems in your code:

  1. You need to define formBuilder instead of just define it with type
export class AppComponent implements OnInit {
    myForm: FormGroup;
    formBuilder: FormBuilder;   // this isn't the right definition of the class;
} 

this should be changed to

 export class AppComponent implements OnInit {
     myForm: FormGroup;
     formBuilder: FormBuilder = new FormBuilder();  
     // or define it by constructor
     // since you are working with typescript you can define in this way
    constructor(private formBuilder: FormBuilder) { }
     // typescript will transform this to  
     // constructor() { 
     //     this.formBuilder = new FormBuilder()
     // }
}
  1. second issue is [formGroup]="myForm" you shoud add formGroup in your template

check reproduction example: https://stackblitz.com/edit/angular-material2-issue-default-select-dppuqx?file=app/app.component.html

Upvotes: 2

Gaël J
Gaël J

Reputation: 15090

When using a FormBuilder, you can pass the initial value of a control as first parameter:

this.formBuilder.control(initialValue, ...)

Upvotes: 1

Related Questions