Angular中this的指向问题

602 阅读1分钟
this.isOpenedCheck = setInterval(this.selectClose, 100);
selectClose(): void {
  if (this.auto.isOpen){ return; }
  if ( this.isOpenedCheck) { clearInterval(this.isOpenedCheck); }

  if ( !this.formControl.value){
    this.formControl.setValue(this.placeholder);
  }
  else if (!this.options.some( option => option === this.formControl.value )){
    this.formControl.setValue(this.placeholder || '');
  }
  this.input.nativeElement.blur();
}

中的this更改了指向,指向了window

1621842485(1).jpg

解决办法:

import * as _ from 'lodash';
 ngOnInit(): void {
 	
    _.bindAll(this, 'selectClose');// 绑定一个对象的方法到对象本身,覆盖现有的方法。
  }

结果

1621842639(1).jpg