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 tag of select element to set default value selected in select box.

Đang xem: Set selected option javascript code example

Technologies Used

Find the technologies being used in our example.1. Angular 11.0.32. Node.js 12.5.03. NPM 6.9.0

1. Using Reactive Form

To set select option selected in reactive form we can use setValue 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 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: >,userName: <"", >,technologies: >});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<3>>;this.userForm.setValue(user);} ——}
We cannot call setDefaultValues method in ngOnInit, ngAfterViewInit in component etc because it will throw error.

1.2. Dynamically Set Value using FormGroup.patchValue

In patchValue 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<3>>;this.userForm.patchValue({profile:userProfile, technologies:userTechnologies});}
Call the setDefaultValues method on user action.

1.3 Create FormGroup with Default Selected Value

If we are not using compareWith, we can set select option selected at FormGroup creation time. Find the example to set default value in single select dropdown.

1.4. Set Default Value with “selected” Attribute

We can also use “selected” attribute in tag of select element to set default value selected in select box.

2. Dynamically Set Value using ngModel in Template-Driven Form

Find the example to set select option selected dynamically using ngModel.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> >;} ——}
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

Run Application

To run the application, find the steps.

Xem thêm:

1. Download source code using download link given below on this page.2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.3. Run ng serve using command prompt.4.

Xem thêm: Top Phần Mềm Hỗ Trợ Chơi Liên Minh Huyền Thoại (2021), Phần Mềm Hỗ Trợ Chơi Game Liên Minh Huyền Thoại

Access the URL http://localhost:4200Find the print screen of the output.

*

References

Angular Select Option + Multiple Select Option + Validation Example using Template-Driven FormAngular Select Option using Reactive Form

Download Source Code

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *