'What the difference between Angular [checked] attribute and formControl setValue?
Why if i update component property, that assigned to [checked] input, in method that called after checkbox changed the value of checkbox doesn't change.
But if i assign Form Control to same checkbox and call setValue checked status of that checkbox will change?
live code example https://codesandbox.io/s/magical-robinson-mzpx9?file=/src/app/app.component.ts
app.component.html
<input
type="checkbox"
[checked]="haveValue"
(change)="valueChanged($event.target)"
[formControl]="checkboxControl"
/>
<dialog #modal>
<form method="dialog">
<button value="default">Ok</button>
<button (click)="cancel()" value="cancel">Cancel</button>
</form>
</dialog>
app.component.ts
export class AppComponent {
haveValue = true;
@ViewChild("modal") modal: ElementRef<HTMLDialogElement>;
checkboxControl = new FormControl(true);
valueChanged(target: EventTarget): void {
const checked = (target as HTMLInputElement).checked;
if (!checked) {
this.modal.nativeElement.showModal();
}
}
cancel(): void {
// if replace with 'this.haveValue = true' checked satus will not changed
this.checkboxControl.setValue(true);
//this.haveValue = true;
console.log("cancel called");
}
}
Solution 1:[1]
Angular bindings react on changes. so this.haveValue = true; should change haveValue from false to true for checkbox to react.
so correct code would look like
valueChanged(target: EventTarget): void {
const checked = (target as HTMLInputElement).checked;
this.haveValue = checked; // here it is changed to false
if (!checked) {
this.modal.nativeElement.showModal();
}
}
cancel(): void {
this.haveValue = true; // back to true
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrei |
