So I stumbled upon this when trying to display users' avatars in mat-select
:
<mat-form-field [formGroup]="assignedToFormGroup">
<mat-select placeholder="Assign to" [(ngModel)]="assignedTo" formControlName="assignTo">
<mat-select-trigger>
<img style="vertical-align:middle;" aria-hidden
src="{{assignedToFormGroup.controls['assignTo'].value.photoUrl}}" height="20" />
<span>@{{assignedToFormGroup.controls['assignTo'].value.userName}}</span>
</mat-select-trigger>
<!-- {{user.userName}} -->
<mat-option *ngFor="let user of members" [value]="user">
<img style="vertical-align:middle;" aria-hidden src="{{user.photoUrl}}" height="20" />
<span>@{{user.userName}}</span>
</mat-option>
</mat-select>
In controller, the formGroup was defined this way:
public assignedToFormGroup: FormGroup;
I followed Sohail's advice and removed [(ngModel)]
from my HTML code:
<mat-form-field [formGroup]="assignedToFormGroup">
<mat-select placeholder="Assign to" formControlName="assignTo">
<mat-select-trigger>
<img style="vertical-align:middle;" aria-hidden
src="{{assignedToFormGroup.controls['assignTo'].value.photoUrl}}" height="20" />
<span>@{{assignedToFormGroup.controls['assignTo'].value.userName}}</span>
</mat-select-trigger>
<!-- {{user.userName}} -->
<mat-option *ngFor="let user of members" [value]="user">
<img style="vertical-align:middle;" aria-hidden src="{{user.photoUrl}}" height="20" />
<span>@{{user.userName}}</span>
</mat-option>
</mat-select>
That gave me errors when opening page - I tried to load photoUrl and userName from null, because by removing [(ngModel)] I also removed default selection in mat-select
.
So I modified my controller to do the following:
1. Constructor:
this.assignedToFormGroup.controls['assignTo'].setValue({photoUrl: '', userName: ''});
Button action where I save my form - added following line:
let assignedTo = this.assignedToFormGroup.controls['assignTo'].value;
That actually worked. Now I'm setting default selection on page load and read selected value when submitting the form.
I'm aware that it's not the best and prettiest solution, but I thought I'll share it - might be a good starting point for better solution.
next
docs: next.angular.io/api/forms/FormControlName#use-with-ngmodel; while v6 is in release candidate the docs still refer to v5. – jonrsharpengModel
for data andformControl
for validation. – Akshay