我试图通过选择“全选”或“全选”来选择垫选的所有字段。这样,如果我选择“全选”或“全选”,我将修补值(作为具有所有元素的数组或空数组)。我试图用“ setValue”代替patchValue和其他一些东西,但是没有用。
重要的是要注意,我第一次选择“全选”可以正常工作,但是第二次是出现ERROR时。谢谢。
代码:
segmentSelected() {
console.log('Entro en segment selected')
var arrayPrepared = [];
var i = 2;
console.log('El array que tenemos una vez entramos es: ')
console.log(arrayPrepared)
console.log('El valor de i que tenemos es:')
console.log(i)
console.log('El tamaño que limita es:')
console.log(Object.keys(this.businessSegmentOptions).length)
var values = this.targetCompaniesForm.controls['business_segment'].value;
if (values.includes('Select All')) {
for (i; i < Object.keys(this.businessSegmentOptions).length; i++) {
arrayPrepared.push((this.businessSegmentOptions)[i])
//console.log('Estoy metiendo el elemento en Business Segments:')
//console.log((this.businessSegmentOptions)[i])
}
this.targetCompaniesForm.controls['business_segment'].patchValue(arrayPrepared, {
emitEvent: false
});
/* var array = this.businessSegmentOptions;
var index = array.indexOf('Select All');
if (index > -1) {
array.splice(index, 1);
} */
}
if (this.targetCompaniesForm.controls['business_segment'].value.includes('Unselect All')) {
this.targetCompaniesForm.controls['business_segment'].patchValue([], {
emitEvent: false
});
}
}
和HTML:
<div id="business_segment" class="col-12 col-md-4 px-0 pl-sm-2 mt-2 m-sm-0">
<label for="segment" class="font-weight-bold">Business Segment</label>
<mat-select placeholder="Select segment" formControlName="business_segment" class="form-control inp-company border-0 text-left" multiple [ngClass]="{'border-bottom-red' : targetCompaniesForm.controls.business_segment.invalid && displayErrors}">
<mat-option (click)="segmentSelected()" *ngFor="let option of businessSegmentOptions" value="{{option}}">{{option}}</mat-option>
</mat-select>
</div>