Goal: Trying to set default value for a dropdown (based on a condition)
Problem: When I remove ngModel it doesn't work. But if I add it back and remove value it also doesnt work. I thought ngModel was supposed to be the feature that affects default value?
What I've tried:
- I went back and reviewed information on data binding and template driven and reactive forms
- I looked up documentation on ngModel. Value was not quite as clear though
- I tried many modifications to mat-select and mat-option
My understanding was that [] did property binding, and allowed the information from Typescript to show up on the webpage (html). [()] allowed for two way binding. and [ngModel] let you take the value from TypeScript and display it. So if you can do 2 way binding with ngModel, what is the purpose of value?
(Context here is an application that has a form, displays a value in the dropdown from database, but allows the user to change the value).
Below is a minimal example of my code:
HTML:
<mat-select [(ngModel)]="myRelationship" placeholder="Relationship to You" formControlName="relationship" required>
<mat-option *ngFor="let rel of relations" [value]="rel.value" (click)="selectRelationship(rel.value)">
{{ rel.viewValue }}
</mat-option>
</mat-select>
Default value doesn't work if you have array of javascript objects with identical values but different viewValues, for example:
relationships = [
{value: Cousin, viewValue: Primo },
{value: Cousin, viewValue: Prima } ]
Conditional logic
if (this.individual.Relationship.startsWith('Cousin')) {
if (this.individual.Gender == 'M') {
this.relations[indexCousin].viewValue = "Primo";
this.relations.push({ value: 'Cousin', viewValue: "Prima" });
}
}