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.

2
  • You want to when you click onPress you display your mycom.html? Commented Nov 11, 2019 at 4:03
  • @devpato. Yes Sir exactly. Actually right now mycomp.html may look stupid but once i know how it is done, then i will extend its code further. Commented Nov 11, 2019 at 4:06

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.