如何在单击事件[Angular]上调用Angular组件

问题描述 投票:0回答:1

我不是Angular的专家。我也从互联网上获得了一些答案。特别是this。我有一个按钮,可以在其中调用用户定义的方法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>';
    }
}

其中mycomp.html是:

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

谁能告诉我该怎么做。

html angular typescript
1个回答
0
投票
<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文件

 ...
 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;*/
 }

工作代码:

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

© www.soinside.com 2019 - 2024. All rights reserved.