4

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.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110

1 Answers1

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

Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
  • 2
    alternatively you can also add new component as sub route using a combination of router and router-outlet then navigate to the route on button click – Joel Joseph Nov 11 '19 at 06:52