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
的引用,只要事件处理程序存在=>它就会造成内存泄漏这是正确的,但最好使用箭头函数
来确保此
的上下文得到保留。请解释您的解决方案。它可以被认为是一种评论,而不是一种回答。