javascript - 如何将 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>
解决方案
正如作者所说,该事件需要动态附加到请求后创建的 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');
}
}
这里有一个功能示例。
推荐阅读
- javascript - 如何在Javascript中根据条件动态包含对象值?
- ldap - 如何在连接到 Keycloak 的 OpenLdap 中读取嵌套组
- sh - sh:比较两个文件后无法返回一个结果
- android - 如何设置服务器以使用 react-native-video 流式传输视频?
- amazon-web-services - 在没有 GCS 的情况下使用 colab TPU
- asp.net - 根路径和文件上传控制
- r - 如何在R中的函数中有不同数量的具有默认值的参数?
- javascript - 滚动到相应部分时无法添加类或样式
- javascript - three.js 中的分层纹理
- python - 美丽的汤 id 对象 null