Reputation: 258
I am trying to use Angular Material form controls. I have a mat-select. When I choose an option, the values get removed, but the choices still display. For example, I am dumping the form values to the screen to observe the behavior. When I select an option, the dumped values on the screen disappear, but the choices still display in the drop-down. What is odd is that is works if I replace mat-select with the native select. Any thoughts as to what I am doing incorrectly?
I replaced mat-select with native select. It works with that, but does not have all of the material design I would like. I have not been able to get it to work per the docs with mat-select.
// This does not work and clears out when an option is selected
<mat-form-field>
<mat-label>Pay Category</mat-label>
<mat-select formControlName="payCategory">
<mat-option *ngFor="let payCategory of payCategories"
[ngValue]="payCategory">
{{payCategory.description}}
</mat-option>
</mat-select>
</mat-form-field>
// This works, but removes some of the material design styling
<mat-form-field>
<mat-label>Pay Category</mat-label>
<select matNativeControl
formControlName="payCategory">
<option *ngFor="let payCategory of payCategories"
[ngValue]="payCategory">
{{payCategory.description}}
</option>
</select>
</mat-form-field>
// In case you wish to see the component relevant code, this is the FormControl...
payCategory: new FormControl( this.buildPayCategories() )
// Pull in payCategories for select list from service
buildPayCategories () {
this.payCategories = this.timeEntry.payCategories;
return this.payCategories;
}
I would rather use the mat-select to take advantage of material design styling rather than having it simply clear out the value selected.
// buildPayCategories returns an array of objects. Here is a sample...
0: {payCategoryId: 1, description: "Converted Data ", payType: "Salary", isActive: true}
Upvotes: 1
Views: 2642
Reputation: 1899
I tried to reproduce your problem but for me it works.
Except instead of [ngValue]
I use [value]
. You can find here on Stackblitz a working example hope it helps.
Edit Based on your update:
public options = [
{payCategoryId: 1, description: "Converted Data ", payType: "Salary", isActive: true},
{payCategoryId: 1, description: "Something Else ", payType: "Salary", isActive: true}
];
public selected = this.options[0];
public payCategory = new FormControl(this.options)
and the template:
<mat-form-field>
<mat-label>Pay Category</mat-label>
<mat-select formControlName="payCategory" [(value)]="selected">
<mat-option *ngFor="let payCategory of options"
[value]="payCategory">
{{payCategory.description}}
</mat-option>
</mat-select>
</mat-form-field>
<p>You selected: {{selected.description}}</p>
This is working just fine, have a look!
Good luck!
Upvotes: 0