我想在Angular组件中访问html元素,并向其添加事件侦听器。但是,当我使用querySelector捕获html元素时,我得到的是空值。
这是我想获得的汉堡班:
<div class="burger">
<div class="line-1"></div>
<div class="line-2"></div>
<div class="line-3"></div>
</div>
这是我的组件ts文件:
import { Component, OnInit } from '@angular/core';
import { NavBarService } from '../../shared/services/nav-bar.service';
import { AuthService } from '../../shared/services/auth.service';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit {
constructor(public nav: NavBarService,
public authService: AuthService,
) { }
ngOnInit() {
this.nav.show();
const navSlide = () => {
const burger = document.querySelector('.burger');
const nav = document.querySelector('nav-links');
burger.addEventListener('click', () => {
nav.classList.toggle('nav-active');
});
}
}
navSlide();
}
当应用程序编译时,出现错误“无法读取null的属性'addeventlistener'。”
您无需手动添加事件监听器。只需使用角度方式:
HTML:
<div (click)="yourFunctionName($event)"></div>
打字稿:
yourFunctionName(event: any) {
alert('Clicked!');
}
请参见指南here
将ViewChild与#localvariable一起使用,如此处所示,
<textarea #variable id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
在组件中
import {ElementRef} from '@angular/core';
@ViewChild('variable') el:ElementRef;
ngAfterViewInit()
{
this.el.nativeElement.focus();
}
这是queryselector代码段:
constructor (private _elementRef : elementRef) {
this._elementRef.nativeElement.querySelector('textarea').focus();
}