lundi 8 juin 2020

Angular 7: How to reset few checkboxes (generated dynamically using *ngFor) to it's previous state only click of a button

I have a child component which consists of 3 checkboxes (generated dynamically using ngFor) and an Apply and Cancel button.

Selector tag for the child is added in the parent's template. Parent component accesses this child component using @ViewChild and calls the present() method exposed by the child component with an object as argument as below which consists of checked state of the checkboxes.

Every time when modal is displayed, present() method is getting called. Even though options.checked value is getting updated in the ts file, this is not getting reflected in the UI. Every time the modal is displayed, I want checkbox to be checked or unchecked based on the value sent by the parent in present() method. Need help.

parent.component.ts:

@ViewChild(childModalComponent) childModalComponent: ChildModalComponent;

onBtnClick() {
 this.childModalComponent.present({
  checkbox1: true,
  checkbox2: false,
  checkbox3: false
 });
}

parent.component.html:

<feature-child-modal></feature-child-modal>

child.component.ts:

 @ViewChild('childModal') childModal: ElementRef;

 ngOnInit() {
    this.options = [
     {
       label: 'label1',
       value: 'value1',
       checked: false,
     },
     {
       label: 'label2',
       value: 'value2',
       checked: false,
     },
     {
       label: 'label3',
       value: 'value3',
       checked: false,
     },
  ];
 }

  present(optionsState: CompressTransactionType) {
    this.options.forEach(item => {
  if(item.value == "value1"){
    item.checked = optionsState.checkbox1;
  }

  if(item.value == "value2"){
    item.checked = optionsState.checkbox2;
  }

  if(item.value == "value3"){
    item.checked = optionsState.checkbox3;
  }
});

this.childModal.nativeElement.present();
}

dismiss() {
  this.childModal.nativeElement.dismiss();
}

child.component.html:

    <div *ngFor="let option of options">
      <input
          type="checkbox" 
          label=""
          [value]="option.value"
          (change)="onOptionsSelectChanged($event)"
          [checked]="option.checked" />
    </div>



Aucun commentaire:

Enregistrer un commentaire