Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(primeng/p-checkbox): support formControlName in multiple mode #15320

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions src/app/components/checkbox/checkbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
ElementRef,
EventEmitter,
forwardRef,
Injector,
Input,
NgModule,
numberAttribute,
Expand All @@ -17,7 +18,7 @@ import {
ViewChild,
ViewEncapsulation
} from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';
import { PrimeTemplate, SharedModule } from 'primeng/api';
import { AutoFocusModule } from 'primeng/autofocus';
import { CheckIcon } from 'primeng/icons/check';
Expand Down Expand Up @@ -235,7 +236,7 @@ export class Checkbox implements ControlValueAccessor {

focused: boolean = false;

constructor(public cd: ChangeDetectorRef) {}
constructor(public cd: ChangeDetectorRef, private readonly injector: Injector) {}

ngAfterContentInit() {
this.templates.forEach((item) => {
Expand Down Expand Up @@ -264,9 +265,18 @@ export class Checkbox implements ControlValueAccessor {
updateModel(event) {
let newModelValue;

/*
* When `formControlName` or `formControl` is used - `writeValue` is not called after control changes.
* Otherwise it is causing multiple references to the actual value: there is one array reference inside the component and another one in the control value.
* `selfControl` is the source of truth of references, it is made to avoid reference loss.
* */
const selfControl = this.injector.get<NgControl | null>(NgControl, null, { optional: true, self: true });

const currentModelValue = selfControl && !this.formControl ? selfControl.value : this.model;

if (!this.binary) {
if (this.checked()) newModelValue = this.model.filter((val) => !ObjectUtils.equals(val, this.value));
else newModelValue = this.model ? [...this.model, this.value] : [this.value];
if (this.checked()) newModelValue = currentModelValue.filter((val) => !ObjectUtils.equals(val, this.value));
else newModelValue = currentModelValue ? [...currentModelValue, this.value] : [this.value];

this.onModelChange(newModelValue);
this.model = newModelValue;
Expand Down
Loading