我在 Angular 8.3 Web SPA 中使用了
我需要在連續范圍內選擇選項的幫助。例如,在影像中,Q2和Q4被選中。我想實作一個功能,如果用戶選擇Q2和Q4,則Q3自動選擇。類似地,如果用戶首先選擇Q3然后選擇Q1,則會Q2自動選擇。總之,在連續范圍內選擇超過 1 個季度時將需要選擇。但是,如果僅選擇四分之一(例如Q4),則無需選擇其他四分之一。
組件.html
<!-- Select quarter -->
<div
>
<ng-multiselect-dropdown
[placeholder]="'Select quarter(s)'"
[settings]="dropdownSettings"
[data]="quarterList"
[(ngModel)]="selectedQuarterList"
(onDropDownClose)="onDropdownClose()"
(click)="this.isDropdownOpen = true"
>
</ng-multiselect-dropdown>
</div>
組件.ts
ngOnInit() {
this.dropdownSettings = {
singleSelection: false,
idField: "quarterId",
textField: "title",
selectAllText: "Select All",
unSelectAllText: "Clear selection",
itemsShowLimit: 4,
allowSearchFilter: false,
};
}
任何與此相同的幫助表示贊賞,謝謝。
uj5u.com熱心網友回復:
ng-dropdown-select 在變數中存盤一個陣列selectedQuarterList。第一個是對這個陣列進行排序,在我們得到這個陣列的第一個和最后一個元素(實際上是索引)并選擇這個陣列之間的所有值之后
所以,首先我們添加事件(onSelect)和(onDeSelect)。我選擇傳遞一個新引數的相同函式,該引數為 true -if select- 或 false -if unselect-
<ng-multiselect-dropdown
...
(onSelect)="onItemSelect($event,true)"
(onDeSelect)="onItemSelect($event,false)"
>
</ng-multiselect-dropdown>
函式 onItemSelect 變得像
onItemSelect(event: any, checked: boolean) {
if (this.selectedQuarterList.length > 1) { //almost two elements selected
//we order the elements acording the list
const value=this.quarterList.filter(x=>this.selectedQuarterList.indexOf(x)>=0)
//get the index of the first and the last element
let first = this.quarterList.findIndex((x) => x == value[0]);
let last = this.quarterList.findIndex(
(x) => x == value[value.length - 1]
);
//and give the value between this indexs
this.selectedQuarterList = this.quarterList.filter(
(_, index) => index >= first && (last < 0 || index <= last)
);
}
}
但是,僅使用此代碼,我們無法取消選中中間的選項 - 假設您已選擇["Q1","Q2","Q3"]它不可能取消選中“Q2”(首先獲取值 0,最后獲取值 2,然后再次選擇“Q2”
為了考慮到這一點,我們需要找到未選中元素的索引并首先和最后更改變數,以便函式變得像
onItemSelect(event: any, checked: boolean) {
if (this.selectedQuarterList.length > 1) {
const value=this.quarterList.filter(x=>this.selectedQuarterList.indexOf(x)>=0)
let first = this.quarterList.findIndex((x) => x == value[0]);
let last = this.quarterList.findIndex(
(x) => x == value[value.length - 1]
);
//we add this condition
if (last - first 1 > value.length && !checked) {
const index = this.quarterList.findIndex((x) => x == event);
if (index < this.quarterList.length / 2) {
first = index 1;
} else
last =index-1;
}
this.selectedQuarterList = this.quarterList.filter(
(_, index) => index >= first && (last < 0 || index <= last)
);
}
}
你可以在這個stackblitz中看到
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345356.html
