【问题标题】:angular append component to respective tabs角度将组件附加到各个选项卡
【发布时间】:2020-03-22 14:59:15
【问题描述】:

我正在尝试使用角度材料和@viewChild 将组件(动态创建)附加到各个选项卡,但只有当我单击第二个选项卡中的按钮时,它才会转到第一个选项卡。

这里是Stackblitz - angular-append-component-to-respective-tabs

它没有显示在单个标签中。我有 3 个标签。所有 3 个选项卡都包含 Add 按钮,当我单击第一个选项卡的按钮时,它会在第一个选项卡中添加该组件,但是当我单击第二个选项卡的 Add 按钮时,它只会在第一个选项卡中添加该组件,它应该添加到第二个选项卡中标签。

有人可以帮我弄清楚如何做到这一点吗?

【问题讨论】:

    标签: angular components angular7 viewchild angular-dynamic-components


    【解决方案1】:

    这里有一个工作示例https://stackblitz.com/edit/angular-append-component-to-respective-tabs-jp5zzt-p7nonq

    使用 ViewChild,您始终可以访问第一个。使用 ViewChildren 并通过 selectedIndex 访问

    【讨论】:

      【解决方案2】:

      您可以使用ViewChildren 代替ViewChild
      @ViewChildren('appenHere', {read : ViewContainerRef}) tabList: QueryList<ViewContainerRef>;
      所以你可以像这样使用它:
      this.componentRef = this.tabList.toArray()[1].createComponent(childComponent);
      您也可以将 index 作为参数传递给 addNewComponent 函数。

      【讨论】:

        【解决方案3】:

        您实现的target 属性始终指向第一个选项卡内的 div。这就是为什么组件总是在那里创建的原因。

        您可以使用ViewChildren 从所有选项卡访问divs 来解决此问题。当用户点击 Append 按钮时,只需将选项卡索引传递给事件处理函数并在正确的选项卡内创建组件。

        示例:https://stackblitz.com/edit/angular-append-component-to-respective-tabs-jp5zzt-aqwxh7

        【讨论】:

          【解决方案4】:

          使用 PrimeNg ang angular Tab 组件在每个选项卡上加载三个组件。

          导入

          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>
          

          创建三个组件并在所有组件中添加添加按钮

          【讨论】:

          • 组件是动态的。请仔细阅读我的问题。我使用的是angular material 而不是PrimeNG。此外,标签是动态的而不是静态的。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-29
          • 1970-01-01
          • 2019-04-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多