HeaderComponent类型上不存在Elementref?

时间:2018-06-29 06:45:45

标签: angular

对编进行编码以检测鼠标在组件内部或组件外部的单击,但显示错误 类型'Headercomponent'上不存在'elementref'

import { OnInit, Input, Output, ElementRef } from '@angular/core';

@Component({
  selector: 'app-header',
  host: {
    '(document:click)': 'handleClick($event)',
  },
  templateUrl: '...........',
  providers: ............,
  styleUrls: ............,
})

export class HeaderComponent {
  constructor(myElement: ElementRef) {
    this.elementRef = myElement;
  }
  handleClick(event) {
    var clickedComponent = event.target;
    var inside = false;
    do {
      if (clickedComponent === this.elementRef.nativeElement) {
        inside = true;
      }
      clickedComponent = clickedComponent.parentNode;
    } while (clickedComponent);
    if (inside) {
      console.log('inside');

    } else {
      console.log('outside');
    }
  }
}

1 个答案:

答案 0 :(得分:-1)

要使用ElementRef,您需要在HTML中具有该元素的引用。因此,对于您要引用的元素,在其上声明一个局部变量并使用ViewChild指令。

TS文件

import { OnInit, Input, Output, ElementRef } from '@angular/core';

@Component({
  selector: 'app-header',
  host: {
    '(document:click)': 'handleClick($event)',
  },
  templateUrl: '...........',
  providers: ............,
  styleUrls: ............,
})

export class HeaderComponent {

  @ViewChild('myElement', { read: ElementRef }) myElement: ElementRef;

  constructor() {
  }

  handleClick(event) {
    var clickedComponent = event.target;
    var inside = false;
    do {
      if (clickedComponent === this.elementRef.nativeElement) {
        inside = true;
      }
      clickedComponent = clickedComponent.parentNode;
    } while (clickedComponent);
    if (inside) {
      console.log('inside');

    } else {
      console.log('outside');
    }
  }
}

HTML文件

<div #myElement>Demo text</div>