问题
I am trying to append component (dynamic created) to respective tabs using angular material and @viewChild
but it is going to first tab only when I click button in the 2nd tab.
Here is Stackblitz - angular-append-component-to-respective-tabs
It's not displaying in individual tab. I have 3 tabs. all 3 tabs contains Add
button, when I click on 1st tab's button, it's adding that component in 1st tab but when I click on 2nd tab's Add
button, it's adding that component in 1st tab only, it should add in 2nd tab.
Can someone please help me to figure-out how to do this?
回答1:
Have a working example here https://stackblitz.com/edit/angular-append-component-to-respective-tabs-jp5zzt-p7nonq
With ViewChild you always access the first one. Use ViewChildren and access with the selectedIndex
回答2:
You can use ViewChildren
instead of ViewChild
.@ViewChildren('appenHere', {read : ViewContainerRef}) tabList: QueryList<ViewContainerRef>;
so you can use it like this:this.componentRef = this.tabList.toArray()[1].createComponent(childComponent);
You can also pass index as parameter to addNewComponent function.
回答3:
The target
property of your implementation always points to the div inside the first tab. Which is why the component is always created there.
You can get around this using ViewChildren
to access the div
s from all the tabs. And when the user clicks on the Append button, simply pass the tab index to the event handler function and create the component inside the correct tab.
Example: https://stackblitz.com/edit/angular-append-component-to-respective-tabs-jp5zzt-aqwxh7
回答4:
Loading Three components on Every tab using PrimeNg ang angular Tab component.
import
import { TabViewModule } from 'primeng/tabview';
import { TabMenuModule } from 'primeng/tabmenu';
html
<tabs id="tabId" #tabsInfo class="tabBorder" style="display: block;">
<tab id="tab1" tabTitle="Tab1">
<tab1Componentselector></tab1Componentselector>
</tab>
<tab id="tab2" tabTitle="Tab2">
<tab2Componentselector></tab2Componentselector>
</tab>
<tab id="tab3" tabTitle="Tab3">
<tab3Componentselector></tab3Componentselector>
</tab>
</tabs>
create three components and Add Add botton in all component.
来源:https://stackoverflow.com/questions/59063676/angular-append-component-to-respective-tabs