Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access child component inside ngb-tab (For validation purposes)

Suppose having this template(for parent component)

<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>

And inside each child component(child-comp1 ...) I have a form and inputs with some validations.

How can I access child's component method from the parent component on demand, I mean something like this:

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;      
}

In parent component I have:

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

comp1 and comp2 are always undefined in the validation method!

tabs return an object, but I couldn't find a way to reach the child component !

like image 473
A.Akram Avatar asked Sep 06 '16 06:09

A.Akram


2 Answers

I had the same issue, a simple fix would be to set destroyOnHide input property to false, which prevents tabs from being destroyed when they get hidden.

<ngb-tabset [destroyOnHide]="false">
  ...
</ngb-tabset>
like image 131
Mehrshad Zandigohar Avatar answered Oct 31 '22 03:10

Mehrshad Zandigohar


In my case issue was connected with two things:

  1. Had to use ngAfterViewInit instead of ngOninit
  2. ngb-tabset was wrapped with *ngIf statement. Changed to [hidden]

P.S for those who encountered this issue when trying to create dynamic component here is the code also for that part:

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()
  }
like image 30
Arsen Khachaturyan Avatar answered Oct 31 '22 04:10

Arsen Khachaturyan