In the given scenario, there is a child component nested in a tab panel defined within the parent component. This setup allows for multiple tab panels and consequently multiple instances of the child component being nested in each tab panel. The goal is to assign a specific value to the child component based on the active tab panel. However, the issue arises when regardless of which tab is selected, the value only updates for Tab 0. To illustrate this problem more effectively, here is a simplified version of the existing code. A functional example can be viewed here: https://stackblitz.com/edit/angular-fd7b3j
To see the issue firsthand, click 'Create Tabs' to generate several tabs and then make Tab 3 the current tab. Subsequently, clicking 'Add One' should ideally update the element value to 4. However, the actual outcome is that the element value in Tab 0 gets updated to 1. Is it possible to direct this action to the correct tab? If so, how?
app.component.html
<p-button label="Create Tabs" (onClick)="handleClick()"></p-button>
<p-button label="AddOne" (onClick)="AddOne()"></p-button>
<p-tabView (onChange)=setIndex($event) [(activeIndex)]="index">
<p-tabPanel #panel [header]="elememt" *ngFor="let elememt of counterList; let i = index" [selected]="i == currentIndex" >
<app-main #main [element]="counterList[i]"></app-main>
</p-tabPanel>
</p-tabView>
app.component.ts
import { Component, ViewChild } from '@angular/core';
import { MainComponent } from './main/main.component';
import { TabViewNav, TabView } from 'primeng/tabview';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'tabViews';
currentIndex = 0;
@ViewChild('main') main: MainComponent;
@ViewChild ('panel') panel: TabView;
counter = 0;
counterList: number[] = [];
index = 0;
handleClick(event: Event) {
this.counterList = [...this.counterList, this.counter];
setTimeout(() => {
this.index = this.counter;
this.currentIndex = this.counter;
this.counter = this.counter + 1;
}, 100);
}
setIndex(event) {
this.currentIndex = event.index;
}
AddOne() {
console.log(this.index);
this.main.element = this.main.element + 1;
}
}
main.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
@Input() element: number;
constructor() { }
ngOnInit() {
}
}
main.component.html
{{element}}