0

I have an edit form with mat-select dropdown list. I want to set the selected item in the dropdown when i go to the edit form .For this im calling a service to get the Current value.

my html:

  <mat-form-field appearance="outline">
                  <mat-select formControlName="organisationUnit" placeholder="Organisation Unit" [(value)]="selected">
                    <mat-option *ngFor="let unit of orgUnits" [value]="unit.id" >
                      {{unit.name}}
                    </mat-option>
                  </mat-select>
                </mat-form-field>

My ts:

  ngOnInit() {

    this.setupFirstFormGroup();
    this.setupSecondFormGroup();
    this.firstFormGroup.get('status').setValue(true);
    this._route.params.subscribe(params => {
      this.tenantAdminService.getUser(params.id).subscribe(res => {
        this.firstFormGroup.get('first_name').setValue(res['first_name']);
        this.firstFormGroup.get('last_name').setValue(res['last_name']);
        this.tenantAdminService.getOrganizationUnit(res['organizationUnit']).subscribe(res => {
          console.log("ORGUNIT", res);
          this.selected = res['id'];

          this.firstFormGroup.get('organisationUnit').setValue(res['id']);

        });

      });
    });

  }

Currently its not setting the value in the dropdown and its empty. Its printing out the value but the selected option doesnt show as selected

Mohit Harshan
  • 1,916
  • 1
  • 18
  • 41

1 Answers1

0

In order to preselect values, you need to bind your model to the select list.

<mat-form-field appearance="outline">
      <mat-select [(ngModel)]="your_model_name" formControlName="organisationUnit" placeholder="Organisation Unit" [(value)]="selected">
           <mat-option *ngFor="let unit of orgUnits" [value]="unit.id" >
                {{unit.name}}
           </mat-option>
       </mat-select>
</mat-form-field>

When you bind the model, and preset the value wanted in the model in your Component, the preselected value will show up in the select list. Also, please note if your dropdown values are not strings, you need to use [ngValue]="..." instead of [value]="..." as value only support the strings.

So now if we use a model myUnit:

...
<mat-select [(ngModel)]="myUnit" ...
...

And in our Component:

this.myUnit = { ... , id: 1}; // pre-selecting a demo unit object

From our dropdown the unit with unit.id = 1 will preselected.

If you get the warning:

It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7

then note: if you are looking for Angular 6 docs then use this. Referring to the depracation from the official docs, there are three possible options if we want to substitute this:
1. use Reactive forms

// html
<mat-form [formGroup]="form"> ... 
    <mat-select formControlName="organisationUnit"> ...
    ....
</form>
// Component: 
this.form.get('organisationUnit').setValue('your preset value');
  1. use Template driven forms
  2. silence this warning (not recommended for use)

    imports: [ ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'}); ]

This similar problem about the deprecation has been asked before and please refer to the original stackoverflow post for comments and answers. I just provided the accepted answer incase the post is deleted and the link becomes obsolete.

Dblaze47
  • 868
  • 5
  • 17
  • is it good to use ngmodel with form control name? I get warning in bowser console that this is going to be deprecated – Mohit Harshan Apr 25 '19 at 06:32
  • Yes the support will be deprecated in the change to Angular v7, but in the meantime you can use it in v6. I have extended my answer to include this scenario, so please check it out. – Dblaze47 Apr 25 '19 at 06:43
  • Im already using reactive forms. i dont see the extended answer, ie,without using ngmodel i want to set the seleceted option – Mohit Harshan Apr 25 '19 at 06:55
  • I have already provided link in my answer of: https://stackoverflow.com/questions/49918503/angular-6-warning-for-using-formcontrolname-and-ngmodel , and in this post this issue has been discussed. I have also provided how to achieve this for reactive forms. Your question was about preselecting data, and that is achieved by binding the model with a preselected data. If you still cannot handle the warning, you have to look through the docs: https://next.angular.io/api/forms/FormControlName#use-with-ngmodel to handle it. – Dblaze47 Apr 25 '19 at 07:11
  • Im using the same set value as you have mentioned.. i have also added this in the question. it doesnt seem to work – Mohit Harshan Apr 25 '19 at 07:32
  • You should set the value to be a model, not only property of the model. The `id` is a field, so instead of `this.selected = res['id'];` try `this.selected = res;`. Bind the entire model. And on select angular will handle displaying the `id` only. – Dblaze47 Apr 25 '19 at 09:37
  • @Mohit glad to know that. Please look up **data binding** as this is a very important thing to grasp when making the `edit` pages or views that will be prefilled with existing data. – Dblaze47 Apr 25 '19 at 12:31