【问题标题】:How to access child component inside ngb-tab (For validation purposes)如何访问 ngb-tab 中的子组件(用于验证目的)
【发布时间】:2016-09-06 06:08:45
【问题描述】:

假设有这个模板(父组件)

<button ... (click)="Save()">
...
<ngb-tabset [activeId]="selectedTab" #tabs>
  <ngb-tab id="tab1">
    <template ngbTabTitle>tab1</template>
    <template ngbTabContent>
      <child-comp1 #comp1>
      </child-comp1>
    </template>
  </ngb-tab>
  <ngb-tab id="tab2">
    <template ngbTabTitle>tab2</template>
    <template ngbTabContent>
      <child-comp2 #comp2>
      </child-comp2>
    </template>
  </ngb-tab>
  ...
</ngb-tabset>

在每个子组件(child-comp1 ...)中,我有一个表单和带有一些验证的输入。

如何从父组件按需访问子组件方法, 我的意思是这样的:

Save(){
  if(Validate()){
    //Save an object ...
  }
}

Validate(){
  if(!this.comp1.Validate()){
    // Activate tab1
    return false;
  }
  else if(!this.comp2.Validate()){
    // Activate tab2
    return false;
  }
  //...
  return true;      
}

在父组件中我有:

// imports ...
@Component({ ... })
export class parent implements OnInit {
  @ViewChild(ChildComp) comp1: ChildComp;
  @ViewChild('comp2') comp2;
  @ViewChild('tabs') tabs;
  ...
  Validate(){...}
  Save(){...}
}

comp1comp2 在验证方法中总是undefined

tabs 返回一个对象,但我找不到到达子组件的方法!

【问题讨论】:

  • 你签入的是构造函数还是ngAfterViewInit()@ViewChild() 尚未在构造函数中分配。还有一些更多的代码会有所帮助。 @ViewChild(....) 和相关代码在哪里。您的问题中显示的 HTML 在哪里?
  • 在点击按钮后的Validate()方法中。
  • @GünterZöchbauer,我稍微更新了这个问题。我希望现在更清楚了!

标签: angular ng-bootstrap


【解决方案1】:

我遇到了同样的问题,一个简单的解决方法是将destroyOnHide 输入属性设置为 false,这样可以防止标签在隐藏时被破坏。

<ngb-tabset [destroyOnHide]="false">
  ...
</ngb-tabset>

【讨论】:

    【解决方案2】:

    在我的情况下,问题与两件事有关:

    1. 必须使用ngAfterViewInit 而不是ngOninit
    2. ngb-tabset*ngIf 语句包裹。改为[hidden]

    对于那些在尝试创建动态组件时遇到此问题的人,这里也是该部分的代码:

    HTML

      <ngb-tabset type="pills" [orientation]="currentOrientation">
        <div #dynamicComponent></div>
      </ngb-tabset>
    

    TS

     @ViewChild('dynamicComponent', { read: ViewContainerRef })
      public viewContainerRef: ViewContainerRef
    
     constructor(   
        private _componentFactoryResolver: ComponentFactoryResolver) {
      }
    
      public ngAfterViewInit(): void {
        const component = this._componentFactoryResolver.resolveComponentFactory(TabComponent)
        const ref = this.viewContainerRef.createComponent(component)
        ref.instance.someValue = 'something'
        ref.changeDetectorRef.detectChanges()
      }
    

    【讨论】:

      【解决方案3】:

      这是因为它们位于 &lt;template&gt; 标记内。这些元素不会像模板中显示的那样创建。 它们在 DOM 中的实际创建方式取决于 &lt;ngb-tab&gt; 对传递给它的模板所做的操作。

      我认为有必要改用ElementRef.nativeElement.querySelector(...) 或类似名称。

      【讨论】:

        猜你喜欢
        • 2021-07-21
        • 2020-05-08
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 2019-02-28
        • 2016-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多