![](/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.