I want to change selected option in select
after click on button
view.html file
<select >
<option *ngFor="let language of outputLanguageList"
value="{{language.shortName}}" >{{language.languageName}}</option>
</select>
<button (click)="changeLanguage()">PL-EN</button>
component.ts file
outputLanguageList:TranslateLanguage[]=[];
ngOnInit(): void {
this.outputLanguageList.push({languageName:"Polski",shortName:"pl"});
this.outputLanguageList.push({languageName:"Angielski",shortName:"en"});
this.outputLanguageList.push({languageName:"Hiszpański",shortName:"es"});
this.outputLanguageList.push({languageName:"Niemiecki",shortName:"de"});
this.outputLanguageList.push({languageName:"Rosyjski",shortName:"ru"});
this.outputLanguageList.push({languageName:"Ukraiński",shortName:"ua"});
this.outputLanguageList.push({languageName:"Słowacki",shortName:"sk"});
}
changeLanguage(){
//code that will change the selected option in selectbox
}
It is possible make this in Angular?
I try do something like this:
changeLanguage(@Inject(DOCUMENT) document:Document){
document.getElementById("asda").value("Polski");
}
But i got error: Property 'value' does not exist on type 'HTMLElement'
CodePudding user response:
You could use the ngModel
directive to update the value (either from the UI, or from the .ts
file):
<select [(ngModel)]="selectedLanguage">
<option *ngFor="let language of outputLanguageList"
value="{{language.shortName}}" >{{language.languageName}}</option>
</select>
<button (click)="changeLanguage()">PL-EN</button>
In the .ts
file you need to declare the selectedLanguage
property and give it an initial value:
public selectedLanguage: string | null = null;
In your changeLanguageMethod
you only need this:
changeLanguage(){
this.selectedLanguage = "Polski";
}
The rest of your code can stay as it is.