![](/img/trans.png)
[英]How to add a property/ styles to child nodes inside a parent element in angular
[英]How to add an Angular property to an HTML element
我需要知道如何通过Javascript将属性(click) = function()
添加到html按钮。
注意:我无法修改HTML,只能通过JavaScript添加属性。
我使用addEventListener进行了测试,它通过添加常见的JavaScript click = "function"
事件而不是Angular的(click)
来工作。
我附上代码:
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侦听click事件。 您的代码应如下所示:
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');
}
}
有一个功能例子在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.