首页 > 解决方案 > 如何将 Angular 属性添加到 HTML 元素

问题描述

我需要知道如何(click) = function()通过 Javascript 将 angular 的属性添加到 html 按钮。

注意:我无法修改 HTML,只能通过 JavaScript 添加属性。

我使用addEventListener进行了测试,它通过添加常见的 JavaScriptclick = "function"事件而不是(click)Angular 来工作。

我附上代码:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-iframe',
  templateUrl: './iframe.component.html',
  styleUrls: ['./iframe.component.scss']
})
export class IframeComponent implements OnInit {
  constructor() {}

  ngOnInit() {
  }

  capture() {         
      let button = document.getElementById('cancelButton').addEventListener('(click)', this.cancel.bind(Event));
  }

  cancel() {
      console.log('Cancelled');
  }
}

和这里的 HTML:

<div class="row text-center pad-md">
  <button id="acceptButton" mat-raised-button color="primary">OK!</button>
  <button id="cancelButton" mat-raised-button>Cancel</button>
</div>

标签: javascripthtmlangular

解决方案


正如作者所说,该事件需要动态附加到请求后创建的 DOM 元素上,因此您可以使用Renderer2 来监听点击事件。您的代码应如下所示:

import { Component, OnInit, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-iframe',
  templateUrl: './iframe.component.html',
  styleUrls: ['./iframe.component.scss']
})
export class AppComponent implements OnInit {
  name = 'Angular';

  constructor(private renderer: Renderer2) {}

  ngOnInit() {}

  capture() {         
      const button = document.getElementById('cancelButton');
      console.log(button);
      this.renderer.listen(button, 'click', this.cancel);
  }

  cancel() {
      console.log('Cancelled');
  }
}

这里有一个功能示例。


推荐阅读