Angular Select Option Set Selected Dynamically
January 09, 2024
This page will walk through how to set values selected in select box dynamically. In reactive form we can use setValue
and patchValue
of FormGroup
and in template-driven form we can use ngModel
to set value in select box dynamically. We can also use 'selected' attribute in <option>
tag of select element to set default value selected in select box.
Contents
1. Using Reactive Form
To set select option selected in reactive form we can usesetValue
and patchValue
of FormGroup
. The setValue
sets the value in each and every form control of FormGroup
. We cannot omit any form control in setValue
but when we want to assign only few form controls of FormGroup then we need to use patchValue
. We can also use 'selected' attribute in <option>
tag of select element to set default value selected in select box.
1.1. Dynamically Set Value using FormGroup.setValue
setValue
sets the value in each and every form control of FormGroup
. Find the example to set select option selected using setValue
dynamically.
user-reactive.component.ts
@Component({ selector: 'app-reactive', templateUrl: './user-reactive.component.html', styleUrls: ['./user.component.css'] }) export class UserReactiveComponent implements OnInit { isValidFormSubmitted = false; allProfiles: Profile[]; allTechnologies: Technology[]; userForm: FormGroup; constructor(private formBuilder: FormBuilder, private userService: UserService) { } ngOnInit(): void { this.userForm = this.formBuilder.group({ profile: [null, [Validators.required]], userName: ['', [Validators.required]], technologies: [null, [Validators.required]] }); this.allProfiles = this.userService.getPofiles(); this.allTechnologies = this.userService.getTechnologies(); } setDefaultValues() { let user = new User(); user.userName = "Narendra Modi"; user.profile = this.allProfiles[2]; user.technologies = [ this.allTechnologies[1], this.allTechnologies[3] ]; this.userForm.setValue(user); } ------ }
setDefaultValues
method on user action.
user-reactive.component.html
<select formControlName="profile"> <option [ngValue]="null" disabled>Choose your profile</option> <option *ngFor="let prf of allProfiles" [ngValue]="prf"> {{ prf.prName }} </option> </select> <select multiple formControlName="technologies" [compareWith]="compareTech"> <option *ngFor="let tech of allTechnologies" [ngValue]="tech"> {{ tech.techName }} </option> </select> <button type="button" (click)="setDefaultValues()">Set Default</button>
setDefaultValues
method in ngOnInit
, ngAfterViewInit
in component etc because it will throw error.
1.2. Dynamically Set Value using FormGroup.patchValue
InpatchValue
method of FormGroup
, we can omit other fields that is not required to be set dynamically.
setDefaultValues() { let userProfile = this.allProfiles[2]; let userTechnologies = [ this.allTechnologies[1], this.allTechnologies[3] ]; this.userForm.patchValue({profile:userProfile, technologies:userTechnologies}); }
setDefaultValues
method on user action.
1.3 Create FormGroup with Default Selected Value
If we are not usingcompareWith
, we can set select option selected at FormGroup
creation time. Find the example to set default value in single select dropdown.
this.userForm = this.formBuilder.group({ profile: this.allProfiles[1], ------ });
1.4. Set Default Value with 'selected' Attribute
We can also use 'selected' attribute in<option>
tag of select element to set default value selected in select box.
<select formControlName="profile" (change)="onProfileChange()"> <option [ngValue]="null" disabled>Choose your profile</option> <option *ngFor="let prf of allProfiles" [ngValue]="prf" [selected]="prf.prId==='dir'"> {{ prf.prName }} </option> </select>
2. Dynamically Set Value using ngModel in Template-Driven Form
Find the example to set select option selected dynamically usingngModel
.
user-templatedriven.component.ts
@Component({ selector: 'app-template', templateUrl: './user-templatedriven.component.html', styleUrls: ['./user.component.css'] }) export class UserTemplateDrivenComponent implements OnInit { allProfiles: Profile[]; allTechnologies: Technology[]; user = new User(); constructor(private userService: UserService) { } ngOnInit(): void { this.allProfiles = this.userService.getPofiles(); this.allTechnologies = this.userService.getTechnologies(); } setDefaultValues() { this.user.userName = "Narendra Modi"; this.user.profile = this.allProfiles[2]; this.user.technologies = [ this.allTechnologies[1], this.allTechnologies[3] ]; } ------ }
setDefaultValues
method on user action.
user-templatedriven.component.html
<select name="profile" [(ngModel)]="user.profile"> <option [ngValue]="null" disabled>Choose your profile</option> <option *ngFor="let prf of allProfiles" [ngValue]="prf"> {{ prf.prName }} </option> </select> <select multiple name="selectedTechs" [compareWith]="compareTech" [ngModel]="user.technologies"> <option *ngFor="let tech of allTechnologies" [ngValue]="tech"> {{ tech.techName }} </option> </select> <button type="button" (click)="setDefaultValues()">Set Default</button>
Find the service class used in our demo application.
user-service.ts
import { Injectable } from '@angular/core'; import { Profile } from '../domain/profile'; import { Technology } from '../domain/technology'; import { User } from '../domain/user'; @Injectable({ providedIn: 'root' }) export class UserService { getPofiles(): Profile[] { let profiles = [ new Profile('dev', 'Developer'), new Profile('man', 'Manager'), new Profile('dir', 'Director') ] return profiles; } getTechnologies(): Technology[] { let technologies = [ new Technology(100, 'Java'), new Technology(101, 'Angular'), new Technology(102, 'Hibernate'), new Technology(103, 'Spring') ] return technologies; } createUser(user: User) { //Log user data in console console.log("User Name: " + user.userName); console.log("Profile Id: " + user.profile.prId); console.log("Profile Name: " + user.profile.prName); for (let i = 0; i < user.technologies.length; i++) { console.log("Technology Id: " + user.technologies[i].techId); console.log("Technology Name: " + user.technologies[i].techName); } } }
References
Angular Select Option using Template-Driven FormAngular Select Option using Reactive Form