Home > Blockchain >  Angular: Hide Child Component of Dynamically Created Parent
Angular: Hide Child Component of Dynamically Created Parent

Time:07-22

I'm working on a POC for an application where I'm just adding and removing rows for a section of the page. Pretty standard layout:

<div [formGroup]="item" *ngFor="let itemof itemArray.controls; let i = index; let isLast = last">
   <input formControlName="itemNumber" />
   <kendo-switch (valueChange)='onToggle($event);'></kendo-switch>
   <child-component [hidden]="hideChild"></child-component>
</div>

On the back end:

hideItem= true;

newItem(): FormGroup {
   return this.fb.group({
      itemNumber: new FormControl(null)
   });
}

addNewItem() {
  this.itemArray.push(this.newItem());
}

onToggle(isEnabled: boolean) {
  this.hideItem= !isEnabled;
}

The problem is that when I try to toggle the visibility of the child component, it toggles for the child for each item, and not just the row I am on. Trying to figure out how to have it only hit the specific child for that row.

CodePudding user response:

You need to hold a state for each control of your itemArray.controls. I suggest you change your hideChild property.

Template :

<div [formGroup]="item" *ngFor="let itemof itemArray.controls; let i = index; let isLast = last">
   <input formControlName="itemNumber" />
   <kendo-switch (valueChange)='onToggle($event, i);'></kendo-switch>
   <child-component [hidden]="hideChild[i]"></child-component>
</div>

Component.ts

hideChild: Record<number, boolean> = {};

newItem(): FormGroup {
   return this.fb.group({
      itemNumber: new FormControl(null)
   });
}

addNewItem() {
  this.itemArray.push(this.newItem());
}

onToggle(isEnabled: boolean, i: number) {
  this.hideChild[i]= !isEnabled;
}
  • Related