coder Tester
coder Tester

Reputation: 155

How can i set a default value in component to a Mat-select triggering (change)

Hello i am trying to set a default value in a mat-select with multiple options in the component.ts, and i am managing to do so, but when i set a default value programatically the method that is supposed to execute when the value changes, does not execute, unless i change the value manually, i'm using (change) directive trigger to the method, is there anything else that i can use? like another directive.

I´m using ngModel to set the default value at the moment, setting a value to object.attribute

<mat-select [compareWith]="compareBasic" id="object" name="object" 
                    [(ngModel)]="object.attribute" (change)="methodThatIWantToTrigger" class="full-width"
                    required> </mat-select>

I should have multiple options in the mat-select, but if there is only one option i want to select that value by default, and i need to know that value that is select in order to get some data from the database. i'm doing something like so:

if (this.array.length == 1){ // if it has only one option
        this.object.attribute = this.array[0];
}

but this leads to some errors or fails.

Upvotes: 0

Views: 2012

Answers (2)

Patryk Brejdak
Patryk Brejdak

Reputation: 1601

It's because mat-select has selectionChange event and it's only fired up when user change it

Event emitted when the selected value has been changed by the user. (angular material docs)

If you want to emit this selectionChange you would have to try with programatically fire event, but you should avoid it. Maybe you can call this method inside your code? Give us your use case, maybe there is a better way.

EDIT

Due to your use case, you could go with ChangeDetectorRef.detectChanges(), so basicly, if you set your default value and you want to be sure, that it is selected in UI you can do something like this. It's a bit hacky, but it will work.

if (this.array.length == 1){ // if it has only one option
        this.object.attribute = this.array[0];
        // this will force to refresh value in mat-select
        this.cdr.detectChanges()
        // here you can call your `methodThatIWantToTrigger` becaucse the view is updated.
}

Also don't forget to add it in your constructor in component.ts and import it Change

import { ChangeDetectorRef } from '@angular/core';    

constructor(private cdr: ChangeDetectorRef) { }

Upvotes: 0

Asanka
Asanka

Reputation: 1648

Since you have 2 way data binding with [(ngModel)] you can use (ngModelChange) instead of (change) . It fires when the value changes. this is stackblitz example

Upvotes: 1

Related Questions