如何在我的Angular组件中获取HTML元素并为其应用事件侦听器?

问题描述 投票:-1回答:2

我想在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'。”

angular dom
2个回答
0
投票

您无需手动添加事件监听器。只需使用角度方式:

HTML:

<div (click)="yourFunctionName($event)"></div>

打字稿:

yourFunctionName(event: any) {
  alert('Clicked!');
}

请参见指南here


0
投票

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();
 }
© www.soinside.com 2019 - 2024. All rights reserved.