Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 load child component on click

Tags:

angular

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.

like image 542
Dino Avatar asked May 03 '17 12:05

Dino


People also ask

How to communicate between parent and child components in angular?

@Input() and @Output() give a child component a way to communicate with its parent component. @Input() lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.


1 Answers

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;
  ...
}
like image 70
longroad Avatar answered Oct 13 '22 00:10

longroad