简体   繁体   中英

Angular: Hide Child Component of Dynamically Created Parent

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM