17

Is it possible to load the child component when button in parent template is clicked? For instance, the parent template html would look like:

<button (click)="loadMyChildComponent();">Load</button>
<my-child-component></my-child-component>

The reason I want to do it like that is because the my-child-component takes some time to load and it slows down everything. Therefore, I'd like to load it only if user clicks to load it. I cannot change the parent template structure. It has to be there.

I want to enter ngOnInit of child's component only when load button is clicked.

5 Answers 5

31

You can use *ngIf directive for the initing component from parent, so your code will be like this

<button (click)="loadMyChildComponent();">Load</button>
<my-child-component *ngIf="loadComponent"></my-child-component>

loadMyChildComponent() {
  loadComponent = true;
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

6

Make use of flag to control the load of child component.

<button (click)="loadMyChildComponent();">Load</button>
<div *ngIf= 'loadComponent'>
<my-child-component></my-child-component>
</div>

In your parent component .ts

 private loadComponent = false;
    loadMyChildComponent(){
       this.loadComponent = true;
    }

Comments

2

You can use perhaps the most fundamental directive ngIf

<button (click)="loadMyChildComponent();">Load</button>
<my-child-component *ngIf="loaded"></my-child-component>

In your component

loadMyChildComponent(){
 loaded=true;
}

Comments

2
<button (click)="loadMyChildComponent()">Load</button>
<div [hidden]="hide">
<my-child-component></my-child-component>
</div>

In parent class declare the varible hide and make a function loadMyChildComponent

 public hide = true;
  loadMyChildComponent(){
       this.hide= true;
    }

3 Comments

Won't this just load and then hide the component? I don't want it to load before clicking on button
any how it is going to be loded after clicking the button instead of that load chlid while the parent gets loaded
@masterfan It wont load your component. You can do console log in ngOnInit() and check.
0

You can use angular directive *ngIf

<button (click)="loadChildComponent();">Load Child Component</button> <child-component *ngIf="childComponentLoaded"></child-component>

in your component.js

public childComponentLoaded: boolean = false;
loadChildComponent() {
    this.childComponentLoaded = true
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.