简体   繁体   English

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

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

I want to access an input element using jquery hidden inside an *ngIf directive. 我想使用隐藏在* ngIf指令内的jquery访问输入元素。 For a simple example : 举个简单的例子:

...
export class ViewChannelScheduleComponent implements OnInit {

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

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

The thing works great, until I decided to hide the component using *ngIf. 事情一直很好,直到我决定使用* ngIf隐藏该组件。 Something like this.. 像这样

...    
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' />

I figured out that immediately after setting the isInputVisible value, jquery is unable to fetch the element. 我发现在设置isInputVisible值后,jQuery无法立即获取该元素。 I verified the thing with a quick hack : 我通过快速破解验证了此内容:

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

Is there any neat way to ask jquery to wait for the element to be visible and callback? 是否有任何巧妙的方法让jquery等待元素可见并回调?

Or any way to reference the input element directly in angular and convert it into jquery object within the function? 或以任何方式直接在angular中引用输入元素并将其转换为函数中的jquery对象?

Let's ignore the part where you are using jquery inside angular and using an ID to reference the element ;) anyways, in your 2nd code example you are using ngOnInit . 让我们忽略在angular中使用jquery并使用ID引用元素的部分;)无论如何,在第二个代码示例中,您将使用ngOnInit In this hook there are no template elements available yet. 在此挂钩中,没有可用的模板元素。 For that you have to go to the ngAfterViewInit hook. 为此,您必须转到ngAfterViewInit挂钩。

But you cannot just change a view property inside that hook, this will give an expression has changed warning. 但是您不能只更改该挂钩内的view属性,这将给出表达式已更改的警告。

If you just want to use it in your showInputBox you can use the ChangeDetectorRef : 如果你只是想在你使用它showInputBox你可以使用ChangeDetectorRef

constructor(readonly cd: ChangeDetectorRef) {}

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

Or just use a setTimeout like you already did, but then without the 100ms: 或者像您一样使用setTimeout ,但是没有100ms:

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

This makes sure it goes to the next change detection loop 这样可以确保它进入下一个更改检测循环

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

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