Tanzeel
Tanzeel

Reputation: 5038

How to call an Angular component on click event [Angular]

I'm not an expert in Angular. I followed some answers from internet also. Specially this. I've a button from where I want to call a user defined method onPress.

app.component.html

<div class="dls-menu-item" style="float: right;">
    <button (click)="onPress()"></button>
</div>

<div id="comp-render">
        <-----Here i want that component to be rendered
</div>

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
    ...
})
export class AnalyticsComponent implements OnInit {
    constructor() {}

    ngOnInit() {}


    onPress() {
        console.log("clicked");
        document.querySelector('#comp-render').innerHTML='<object type="text/html" data="mycomp.html" ></object>';
    }
}

Where mycomp.html is:

<h1>Hello</h1>
<p>This is a custom component.</p>
<button>Click</button>

Can anyone please tell me how to do it.

Upvotes: 4

Views: 49557

Answers (1)

Patricio Vargas
Patricio Vargas

Reputation: 5522

<div class="dls-menu-item" style="float: right;">
    <button (click)="onPress()"></button>
</div>

<div id="comp-render" *ngIf="display">
    <mycomp></mycomp>
</div>

app.component.ts file

 ...
 display = false;
 onPress() {
   this.display = true;
   /*if you want the component to show and hide on click pressed, use 
   use this line
   this.display = !this.display;*/
 }

Working code:

https://stackblitz.com/edit/angular-d21pkn

Upvotes: 13

Related Questions