Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mat-select value dosen't work with formControlName

I am using mat-select ,I need to set default value for it. It works but After adding formControlName to it, its default value is not displayed.

I tried [(ngModel)] and [(value)] , and "mat-autocomplete"

<mat-form-field>
 <mat-select placeholder="پیش نمایش" 
   formControlName="lesson" 
     [value]="free_demo"
      (selectionChange)="onSelectDemo(i)">
      <mat-option [value]="demo.id"
       *ngFor="let demo of demos[i]">
        {{ demo.title }}
       </mat-option>
   </mat-select>

like image 989
mahsa yadegari Avatar asked Jul 04 '19 07:07

mahsa yadegari


People also ask

How do you bind a value in mat select?

Create Select using <mat-select> To add elements to select option, we need to use <mat-option> element. To bind value with <mat-option> , we need to use value property of it. The <mat-select> has also value property to bind selected value to keep it selected. We need to use <mat-select> inside <mat-form-field> element.


2 Answers

If you are using "formControlName" you can access the controller in the TS file and set value like:

this.yourFormName.controls['lesson'].setValue('your value or' + this.dynamicValue )
like image 65
Atul Stha Avatar answered Sep 29 '22 01:09

Atul Stha


When it comes to using reactive forms, I would recommend you to set/update your FormControl by using the setValue() or patchValue() methods. You may read up more about it over here.

This is one way you can update your form values using patchValue. Assuming the object has a id of 1,

this.editProductForm.patchvalue({
  sub_products: [{
    lesson: '1'
  }]
});

On your component.ts,

<mat-form-field>
 <mat-select placeholder="پیش نمایش" 
   formControlName="lesson" 
   (selectionChange)="onSelectDemo(i)">
   <mat-option [value]="demo.id" *ngFor="let demo of demos[i]">
     {{ demo.title }}
   </mat-option>
 </mat-select>
</mat-form-field>
like image 34
wentjun Avatar answered Sep 28 '22 23:09

wentjun