'Angular 12 pass data to child in ngFor

I'ma having a trouble passing data to child in ngFor put in a PrimeNg TabPanel. The parent is like:

<p-tabPanel header="{{tab.title}}" *ngFor="let tab of tabs; let i = index" [closable]="true" [selected]="active[i+1]">
   <app-edit-tab [profile]="profiles[i]" (profileModifiedEvent)="profileModifiedEvent($event, i)"></app-edit-tab>
</p-tabPanel>

Child component is an edit tab and contains:

@Component({
    selector: 'app-edit-tab',
    templateUrl: './edit-tab.component.html'        
})
export class EditTabComponent implements OnInit {
    @Input() profile: Profile;
    backupProfile: Profile;
    @Output() profileModifiedEvent: new EvenEmitter<Profile>();

    ngOnInit() {
        this.backupProfile = Object.assign({}, profile);
    }

    editProfile() {
        this.profileModifiedEvent.emit(this.profile);
    }
}

I make a backup copy for reset edited fields, and I use input profile object as model in template. If I open 2 tabs, I check in onInit that backup copy is right: the first tab, contains a copy of the first profile passed, call it A, the second tab, contains a copy of the second profile passed, call it B. The problem is that, in second tab, when editProfile() is called, the profile object isn't B, but A! It's like the second tab has the content of profile A but I checked in onInit that profile was B! Is there a way to solve this problem? It's need to have a copy of the input Profile object for each tab.

EDIT: Maybe the real question is: which is the best way to pass argument, taken from array, to child component?



Solution 1:[1]

If I were you I would try the lifecycle hook ngOnChanges(). Although I do not know your exact use case/problem from what you have provided, there is a chance that your child component is rendering the first time with the @Input() value set to a certain value. Then when the value changes in the parent it is not automatically updated in the child because this is how Angular works.

Use ngOnChanges() {} to detect the change and update your @Input() value accordingly!

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 mikegross