Remove Selected Option From Drop Down In Angular
I have a button which adds more select drop downs when clicked. So I would like to remove the already selected options in these select boxes for preventing duplication. The followi
Solution 1:
You can try create two objects of environments and listen selection with valueChanges from formControl. After you get the selected environmentid and filter the other object without this id
Example
ngOnInit(){
this.createForm();
this.getEnvironments();
this.environmentChanges()
}
createForm(){
this.form = this.fb.group({
'environment_id_1': [''],
'environment_id_2' : ['']
})}
getEnvironments(){
const environments = [
{ 'environment_id': 1, 'environment': 'A' },
{ 'environment_id': 2, 'environment': 'B' },
{ 'environment_id': 3, 'environment': 'C' },
{ 'environment_id': 4, 'environment': 'D' }];
this.environments1 = environments;
this.environments2 = environments;}
environmentChanges(){
this.form.controls['environment_id_1'].valueChanges
.subscribe((environment_id)=>{
this.environments2 = this.environments1.filter((env)=> env.environment_id != environment_id)
})}
<form [formGroup]="form">
<divclass="row"><selectclass="select form-control"formControlName="environment_id_1"><optionvalue="">Select Environment 1 </option><option *ngFor="let environment of environments1" [value]="environment.environment_id"> {{environment.environment}} </option></select></div><divclass="row"style="padding-top: 10px;"><selectclass="select form-control"formControlName="environment_id_2"><optionvalue="">Select Environment 2 </option><option *ngFor="let environment of environments2" [value]="environment.environment_id"> {{environment.environment}} </option></select></div>
Post a Comment for "Remove Selected Option From Drop Down In Angular"