Reputation: 288
So I have two ng-select in my code, and if I select first ng-select value, I want to hide the same select option from the second ng-select. But I dont know how to control it. I wanted to use Jquery with, but no chance. Both sourceLangCodeList and targetLangCodeList has values [ EN, KR ] So the thing I want to try, once I select the value of one of ng-select, hide the same value the second ng-select has. Plz help!
<td>
<div class="form-group">
<ng-select
id="sourceLangSelect"
bindLabel="language"
bindValue="language"
formControlName="sourceLangCode"
[items]="sourceLangCodeList"
(change)="onChange($event)"
></ng-select>
</div>
</td>
<td></td>
<td>
<div class="form-group">
<ng-select
id="targetLangSelect"
bindLabel="language"
bindValue="language"
formControlName="targetLangCode"
[items]="targetLangCodeList"
></ng-select>
</div>
</td>
Upvotes: 0
Views: 2470
Reputation: 2165
Since you are using ReactiveForms, I will answer in ReactiveForm way. Check out the full code at https://stackblitz.com/edit/m3yevn-ng-select-demo
Template:
<div class="form-group" [formGroup]="formGroup">
<ng-select id="sourceLangSelect" bindLabel="language" bindValue="language" formControlName="sourceLangCode"
[items]="sourceLangCodeList"></ng-select>
<ng-select id=" targetLangSelect" bindLabel="language" bindValue="language" formControlName="targetLangCode"
[items]="targetLangCodeList"></ng-select>
</div>
Component
import { Component, Input } from "@angular/core";
import { FormControl, FormGroup } from "@angular/forms";
import { Subscription } from "rxjs";
@Component({
selector: "ng-select-demo",
templateUrl: "./ng-select-demo.component.html",
styles: [
`
h1 {
font-family: Lato;
}
`
]
})
export class NgSelectDemo {
@Input() name: string;
sub = new Subscription();
originalLangCodeList = [
{ language: "" },
{ language: "en" },
{ language: "kr" },
{ language: "zh-cn" },
{ language: "ru" }
];
targetLangCodeList = [...this.originalLangCodeList];
sourceLangCodeList = [...this.originalLangCodeList];
formGroup = new FormGroup({
sourceLangCode: new FormControl(""),
targetLangCode: new FormControl("")
});
ngOnInit() {
this.sub.add(
this.formGroup.controls["sourceLangCode"].valueChanges.subscribe(
value => {
this.targetLangCodeList = this.originalLangCodeList.filter(
langObj => langObj.language !== value
);
}
)
);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
TLDR;
Upvotes: 1
Reputation: 725
Please add a ngModel to slectedSoureclang and Onchange Filter the targetLangCodeList
<ng-select
id="sourceLangSelect"
bindLabel="language"
bindValue="language"
formControlName="sourceLangCode"
[items]="sourceLangCodeList"
(change)="onChange($event)"
[(ngModel)]="selectedSourceLang"
></ng-select>
Change Event
onChange(event){
const newlist = targetLangCodeList.filter((lang)=>lang!==this.selectedSourceLang);
targetLangCodeList = [...newlist];
}
Upvotes: 1