如何在点击事件中调用Angular组件[Angular]

Tan*_*eel 0 html typescript angular

我不是Angular的专家。我也从互联网上获得了一些答案。特别是这个。我有一个要从中调用用户定义方法的按钮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>
Run Code Online (Sandbox Code Playgroud)

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>';
    }
}
Run Code Online (Sandbox Code Playgroud)

其中mycomp.html是:

<h1>Hello</h1>
<p>This is a custom component.</p>
<button>Click</button>
Run Code Online (Sandbox Code Playgroud)

谁能告诉我该怎么做。

dev*_*ato 5

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

<div id="comp-render" *ngIf="display">
    <mycomp></mycomp>
</div>
Run Code Online (Sandbox Code Playgroud)

app.component.ts文件

 ...
 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;*/
 }
Run Code Online (Sandbox Code Playgroud)

工作代码:

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

  • 或者,您也可以使用路由器和路由器出口的组合添加新组件作为子路由,然后单击按钮导航到该路由 (2认同)