Reputation: 105
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
Reputation: 4453
I could see 2 problems in your code:
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()
// }
}
[formGroup]="myForm"
you shoud add formGroup in your templatecheck reproduction example: https://stackblitz.com/edit/angular-material2-issue-default-select-dppuqx?file=app/app.component.html
Upvotes: 2
Reputation: 15090
When using a FormBuilder
, you can pass the initial value of a control as first parameter:
this.formBuilder.control(initialValue, ...)
Upvotes: 1