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

2024-05-07

我不是 Angular 方面的专家。我也遵循了互联网上的一些答案。特别this https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript。我有一个按钮,我想从中调用用户定义的方法onPress.

应用程序组件.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>

应用程序组件.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>

谁能告诉我该怎么做。


<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 https://stackblitz.com/edit/angular-d21pkn

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在点击事件上调用 Angular 组件 [Angular] 的相关文章

随机推荐