如何通过按下按钮 select 所有 select2 个元素?
How to select all select2 elements, by pressing a button?
我正在使用 angular 的 Select2 组件作为多个 selector。我需要通过单击按钮或复选框来 select 所有元素的选项。
https://www.npmjs.com/package/ng-select2
我尝试在按下按钮时插入数组 [(ngModel)] = "value" 所有元素的 ID,但没有成功
.HTML 代码
<ng-select2 [data]="exampleData"
[options]="options"
[width]="200"
[(ngModel)]="value"
(valueChanged)="onTagChanged($event)">
</ng-select2>
<button (click)='selectAll()'>Select all</button>
.TS 代码
ngOnInit() {
this.exampleData = [
{
id: '0',
text: 'Pau Cano Dominguez',
},
{
id: '2',
text: 'Miguel Ángel Vargas Gomez'
},
{ id: '3',
text: 'Pedro Medina Cruz'
},
{ id: '4',
text: 'Oriol Fuentes Nuñez'
},
{
id: '5',
text: 'Rayan Mora Sanchez'
}
];
this.options = {
width: '200',
multiple: true,
tags: false
};
}
selectAll() {
console.log('Select All Pushed');
this.value.push('0');
this.value.push('1');
this.value.push('2');
this.value.push('3');
this.value.push('4');
}
ng-select2 组件正在使用 OnPush 更改检测策略。
这意味着它只会在检测到其输入已更新时才会更新自身。
你可以在 ng-select2 中看到这个 component code at line 31
现在数组通过引用传递,这就是组件未检测到任何更改的原因。您需要做的是传入一个新数组。
所以在你的 selectAll 函数中改为这样做:
this.value = ['0', '1', '2', '3', '4']; // this passes a new array reference
了解有关变更检测的更多信息here's a good read
我正在使用 angular 的 Select2 组件作为多个 selector。我需要通过单击按钮或复选框来 select 所有元素的选项。 https://www.npmjs.com/package/ng-select2
我尝试在按下按钮时插入数组 [(ngModel)] = "value" 所有元素的 ID,但没有成功
.HTML 代码
<ng-select2 [data]="exampleData"
[options]="options"
[width]="200"
[(ngModel)]="value"
(valueChanged)="onTagChanged($event)">
</ng-select2>
<button (click)='selectAll()'>Select all</button>
.TS 代码
ngOnInit() {
this.exampleData = [
{
id: '0',
text: 'Pau Cano Dominguez',
},
{
id: '2',
text: 'Miguel Ángel Vargas Gomez'
},
{ id: '3',
text: 'Pedro Medina Cruz'
},
{ id: '4',
text: 'Oriol Fuentes Nuñez'
},
{
id: '5',
text: 'Rayan Mora Sanchez'
}
];
this.options = {
width: '200',
multiple: true,
tags: false
};
}
selectAll() {
console.log('Select All Pushed');
this.value.push('0');
this.value.push('1');
this.value.push('2');
this.value.push('3');
this.value.push('4');
}
ng-select2 组件正在使用 OnPush 更改检测策略。 这意味着它只会在检测到其输入已更新时才会更新自身。
你可以在 ng-select2 中看到这个 component code at line 31
现在数组通过引用传递,这就是组件未检测到任何更改的原因。您需要做的是传入一个新数组。 所以在你的 selectAll 函数中改为这样做:
this.value = ['0', '1', '2', '3', '4']; // this passes a new array reference
了解有关变更检测的更多信息here's a good read