【问题标题】:How to call an Angular component on click event [Angular]如何在点击事件上调用 Angular 组件 [Angular]
【发布时间】:2019-11-11 03:47:15
【问题描述】:

我不是 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>

谁能告诉我怎么做。

【问题讨论】:

  • 你想在点击时显示你的mycom.html吗?
  • @devpato。是的,先生。实际上现在 mycomp.html 可能看起来很愚蠢,但是一旦我知道它是如何完成的,那么我将进一步扩展它的代码。

标签: html angular typescript


【解决方案1】:
<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

【讨论】:

  • 或者,您也可以使用路由器和路由器插座的组合添加新组件作为子路由,然后单击按钮导航到路由
猜你喜欢
  • 2019-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2017-04-05
  • 2021-09-03
  • 2018-10-13
  • 2018-10-22
相关资源
最近更新 更多