Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website.
Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Value, none of the suggested solutions have been successful in achieving the desired outcome.
What seems to be the issue? Is it necessary to use a form/mat-form or is there a more straightforward approach available?
Approaches Tried: Below are some of the different methods attempted in both the HTML and TypeScript code:
<mat-select (selectionChange)="doSomething($event)" [value]="language">
<mat-select (selectionChange)="doSomething($event)" [value]="English">
<mat-select (selectionChange)="doSomething($event)" [(ngModel)]='defaultLanguage'>
HTML Code:
<form [formGroup]="_siteForm">
<mat-form-field class="right">
<mat-select (selectionChange)="doSomething($event)" [(ngModel)]='defaultLanguage'>
<mat-option *ngFor="let language of languages" [value]="language">
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
TypeScript Code:
public _siteForm : FormGroup;
this._siteForm = fb.group({
'languages' : ['']
});
public languages = [
{ value: "en", viewValue: 'English' },
{ value: "es", viewValue: 'Spanish' }
];
public defaultLanguage : string = "English";
if (this.localeId == "en") { this._siteForm.controls["languages"].setValue(this.languages.filter(item => item.value === 'en')[0].viewValue); }
else { this._siteForm.controls["languages"].setValue(this.languages.filter(item => item.value === 'es')[0].viewValue); }
Another Method
this._siteForm.setValue({ languages: "en" });