Как сделать опции allSelected если выбрана другая опция?
Подскажите что не так делаю, сейчас у меня если выбрана опция в селекте allSelected и я выбираю любую из списка то allSelected пропадает заменяясь на новую опцию, а как теперь сделать наоборот что б если у меня выбрана любая опция кроме allSelected, и я б выбирал allSelected то все опции б исчезали кроме allSelected, что не так ?
this.form.get('selectedOptions').valueChanges.subscribe((options: string[]) => {
if (options.length > 1 && options.includes('allSelected')) {
const withoutAllSelected = options.filter(option => option !== 'allSelected');
this.form.get('selectedOptions').patchValue(withoutAllSelected, { emitEvent: false });
} else if (options.length > 1 && !options.includes('allSelected')) {
const withoutAllOptionsSelected = options.filter(option => option !== 'allSelected');
this.form.get('selectedOptions').patchValue(withoutAllOptionsSelected, { emitEvent: false });
}
});
Ответы (1 шт):
Автор решения: Артем Мишуровский
→ Ссылка
Решил с помощью функции pairwise() из библиотеки RxJs:
this.form.get('selectedOptions').valueChanges
.pipe(startWith(this.form.get('selectedOptions').value),
pairwise())
.subscribe(([previousOptions, currentOptions]: [string[], string[]]) => {
const allSelectedIndex = currentOptions.indexOf('allSelected');
if (allSelectedIndex !== -1 && previousOptions.length > 1 && !previousOptions.includes('allSelected')) {
this.form.get('selectedOptions').setValue(['allSelected'], { emitEvent: false });
} else if (currentOptions.length > 1 && currentOptions.includes('allSelected')) {
const withoutAllSelected = currentOptions.filter(option => option !== 'allSelected');
this.form.get('selectedOptions').patchValue(withoutAllSelected, { emitEvent: false });
}
});