gpt4 book ai didi

angular - 如何在 Angular 8 中为 viewchild 元素引用编写点击事件

转载 作者:行者123 更新时间:2023-12-05 08:51:24 25 4
gpt4 key购买 nike

尝试在 typescript 中为元素引用单击事件但不起作用。如何为元素引用编写单击事件。如果有人知道请帮助找到解决方案。

应用程序组件.ts:

@ViewChild('testElem') el:ElementRef;
@ViewChild('testElem2') el2:ElementRef;

this.el.on('click',()=>{
alert("test");
});

应用程序组件.html:

<div #el>testElem</div>

<div #el2>testElem2</div>

最佳答案

你可以做这样的事情:

app.component.html

<div #el">testElem</div>

app.component.ts

import { AfterViewInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'
import { fromEvent, Subscription } from 'rxjs';

@Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
export class AppComponent implements AfterViewInit {

@ViewChild('el', { static: false}) el: ElementRef;

clickedElement: Subscription = new Subscription();

ngAfterViewInit() {
this.clickedElement = fromEvent(this.el.nativeElement, 'click').subscribe(() => console.log('element clicked'));
}

ngOnDestroy() {
// add this for performance reason
this.clickedElement.unsubscribe();
}
}

我们正在使用 AfterViewInit Hook ,因为 DOM 已经存在于此处。

希望我能帮到你。

关于angular - 如何在 Angular 8 中为 viewchild 元素引用编写点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60004074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com