0

I want to change selected option in select after click on button

view.html file

<select class="language-selector">
  <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'

1 Answer 1

1

You could use the ngModel directive to update the value (either from the UI, or from the .ts file):

<select class="language-selector" [(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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.