Tengo una lista de opciones para selección múltiple. en una de las opciones, debo agregar otro campo de comentario de campo. así que seleccionando en la primera vez añadir este campo. pero al eliminar la selección, no elimina esta selección de la matriz porque no eliminé el campo de comentarios. entonces, cuando seleccione esta opción nuevamente, agregará dos veces el mismo índice (uno con el campo de comentario y otro con nulo en el comentario) Necesito establecer el valor solo si no tengo este índice en la matriz
<p-multiSelect [required]="formGroup.hasError('remark-reasons-required')" [options]="reasons" defaultLabel="" formControlName="remarks" optionLabel="hebName" selectedItemsLabel="{0} " (onChange)="onChangeReasonsValue($event)"></p-multiSelect> 
onChangeReasonsValue(event: { value: ReviewDecisionReasonModel[] }): void { // var selectedArray = event.value.filter(function (item, pos) { return event.value.indexOf(item) == pos; }) this.formGroup.get('remarks').setValue(selectedArray); this.selectedReasons = selectedArray; this._decision.reasons = selectedArray; }Parece que el componente de selección múltiple tiene un error, donde las opciones deshabilitadas/eliminadas del componente permanecen agregadas al formControl relacionado.
Le propongo que agregue una propiedad "deshabilitada" a sus opciones y configure esta opción a medida que cambian las selecciones en lugar de agregarlas o eliminarlas. Después de eso, puede ajustar los valores de formulario con solo las opciones habilitadas.
Además, no podría usar (OnChange) a favor de suscribirse a los cambios de formulario del componente.
algo como
otherReasonWhen2 = { id: 3, hebName: 'heb3', freeTextAllow: false, disabled: true }; reasons = [ { id: 1, hebName: 'heb1', freeTextAllow: false, disabled: false }, { id: 2, hebName: 'heb2', freeTextAllow: false, disabled: false }, this.otherReasonWhen2, ]; ngOnInit() { this.formGroup.get('remarks').valueChanges.subscribe((newValues) => { console.log(newValues) // This is here for you to see the values as they change this.otherReasonWhen2.disabled = newValues.every(reason => reason.id !== 2) if (newValues.some(reason => reason.disabled)){ // work-around for the observed bug: when there are disabled options selected, remove them from the form. this.formGroup.get('remarks').setValue(newValues.filter(reason => !reason.disabled)); } }); }y no olvide agregar la directiva para deshabilitar la opción:
<p-multiSelect [options]="reasons" optionDisabled="disabled" <-- Here defaultLabel="" formControlName="remarks" optionLabel="hebName" selectedItemsLabel="{0} " ></p-multiSelect>