繁体   English   中英

jQuery:角* ngIf指令内的访问元素

[英]jquery : access element inside an angular *ngIf directive

我想使用隐藏在* ngIf指令内的jquery访问输入元素。 举个简单的例子:

...
export class ViewChannelScheduleComponent implements OnInit {

   someFunction() {
   ...
      doSomething($('#my-input'));
   ...
   }
}
...

<!-- and finally -->
<input id='my-input' />

事情一直很好,直到我决定使用* ngIf隐藏该组件。 像这样

...    
export class ViewChannelScheduleComponent implements OnInit {

   isInputVisible = false;

   ngOnInit() {
      this.isInputVisible = true;
      doSomething($('#my-input')); //unable to catch element
   }

}
...

<!-- and finally -->
<button (click)="showInputBox()">Enable</button>
<input *ngIf="isInputVisible" class='date-time-picker' />

我发现在设置isInputVisible值后,jQuery无法立即获取该元素。 我通过快速破解验证了此内容:

showInputBox() {
   this.isInputVisible = true;
   setTimeout(doSomething($('#my-input')), 100); //this works
}

是否有任何巧妙的方法让jquery等待元素可见并回调?

或以任何方式直接在angular中引用输入元素并将其转换为函数中的jquery对象?

让我们忽略在angular中使用jquery并使用ID引用元素的部分;)无论如何,在第二个代码示例中,您将使用ngOnInit 在此挂钩中,没有可用的模板元素。 为此,您必须转到ngAfterViewInit挂钩。

但是您不能只更改该挂钩内的view属性,这将给出表达式已更改的警告。

如果你只是想在你使用它showInputBox你可以使用ChangeDetectorRef

constructor(readonly cd: ChangeDetectorRef) {}

showInputBox() {
   this.isInputVisible = true;
   this.cd.detectChanges();
   doSomething($('#my-input');
}

或者像您一样使用setTimeout ,但是没有100ms:

showInputBox() {
   this.isInputVisible = true;
   setTimeout(() => doSomething($('#my-input'));
}

这样可以确保它进入下一个更改检测循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM