Home  >  Angular

Angular Select Option Set Selected Dynamically

By Arvind Rai, May 02, 2019
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.

Technologies Used

Find the technologies being used in our example.
1. Angular 7.0.0
2. Angular CLI 7.0.3
3. TypeScript 3.1.1
4. Node.js 10.3.0
5. NPM 6.1.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 <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);
	}
    ------
} 
Call the 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>	 
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[1],
		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.
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 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]
          ];
	}
        ------
} 
Call the 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>	

Run Application

To run the application, find the steps.
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. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Select Option Set Selected Dynamically

References

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

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us