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 !
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>
In my case issue was connected with two things:
ngAfterViewInit
instead of ngOninit
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With