Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 有没有办法在ngAfterViewInit方法内的Jquery事件处理程序内调用typescript方法_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 有没有办法在ngAfterViewInit方法内的Jquery事件处理程序内调用typescript方法

Javascript 有没有办法在ngAfterViewInit方法内的Jquery事件处理程序内调用typescript方法,javascript,angular,typescript,Javascript,Angular,Typescript,我使用的是Angular 4。想从ngAfterViewInit方法调用typescript文件的方法吗 declare var $; @Component({ selector: 'app-details', templateUrl: './details.component.html', styleUrls: ['./details.component.css'] }) export class DetailsComponent implements OnInit ,Af

我使用的是
Angular 4
。想从
ngAfterViewInit
方法调用typescript文件的方法吗

 declare var  $;
 @Component({
 selector: 'app-details',
 templateUrl: './details.component.html',
 styleUrls: ['./details.component.css']
})    
export class DetailsComponent implements OnInit ,AfterViewInit{
    ngAfterViewInit(): void {
    $(document).on("hide.bs.modal", function () {
         //this.setValueInsideDetailForm(); This is methods inside typescript file , which one i want to call
     });
    }
  setValueInsideDetailForm(){
       // Some code here.
   }

}

但是它会抛出错误,比如
setValueInsideDetailForm
未定义。

您的函数正在从组件获取
上下文。在
$
类型
const self=this之前并改用
self

尝试在回调函数中记录此
,查看它记录的内容。

尝试:

ngAfterViewInit(): void {
    $(document).on("hide.bs.modal", () => {
        this.setValueInsideDetailForm();
    });
}
您需要使用箭头函数才能访问当前范围之外的方法

myFirstMethod() {
  console.log('my first method');
}

myMethod() {
  this.myFirstMethod() // Works

  function test() {
     this.myFirstMethod() // Does not work because it is restricted to what 
                             is inside of the test() method
  }

  const test = () => {
    this.myFirstMethod() // Works since is not restricted to test method 
                            scope
  }

}

处理程序使用arrow函数保持相同的上下文,JQuery与Angular是一种反模式:您不应该自己处理DOM事件。相反,使用一个库来实现Angular的引导,例如。这样做是不好的行为。它使用变量
self
保留对
this
的引用,只要事件处理程序存在=>它就会造成内存泄漏这是正确的,但最好使用
箭头函数
来确保
的上下文得到保留。请解释您的解决方案。它可以被认为是一种评论,而不是一种回答。