0

I have a very simple angular material select component that's filled from an array of objects. I tried the double way binding with ngModel and the component select attribute but both don't work as expected.

What I am expecting: Changing the selected option updates the ngModel value with accordingly.

What actually happens: Changing the selected option fires the select change method but don't update the binded attribute.

How to reproduce: Select the Option2 and then go back to Option1, play only with 2 options.

Where to reproduce: https://stackblitz.com/edit/angular-qpk2di

2
  • the stackblitz works for me. I see the selected value being updated, and the binding selectedOption.value as well. Switching between 1 -> 2 -> 1 -> 2 Commented Jul 5, 2018 at 8:55
  • What browser are you using, because I tested on Firefox and Chrome latest versions and both are not working correctly Commented Jul 5, 2018 at 8:57

2 Answers 2

3

So your error is actually not that complicated you have wrongly used the [()] braces

  1. [] is to bind a value to a variable
  2. () is for event handling

you used a eventhandler and "databinder" on value [(value)], but you only want to bind

[value] = "selected option"

the event is handled with the (selectionOnChange)="handleYourEvent()" event

Sign up to request clarification or add additional context in comments.

1 Comment

You are my superhero :D Thanks a lot
0

You can transform your object into a string with JSON.stringify to bind it and after reparse it into an object with JSON.parse to use it in your TS file.

In your ts file : 

stringifyValue(value) {
    return JSON.stringify(value); 
}

parseValue(value) {
    let selectedObj = JSON.parse(value); 
}

in your html :

<mat-select (selectionChange)="parseValue($event.value)" >
   <mat-option *ngFor="let obj of options" 
   [value]="stringify(obj)">{{ obj.name }}
   </mat-option>
</mat-select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.