我希望使用隐藏在*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等待元素可见并回调吗?
或者用任何方式直接引用输入元素,并将其转换为函数中的jquery对象?
发布于 2018-09-07 12:31:11
让我们忽略在角内使用jquery并使用ID引用元素的部分;)无论如何,在第二个代码示例中,您使用的是ngOnInit
。在这个钩子中还没有可用的模板元素。为此,您必须使用ngAfterViewInit
钩子。
但是您不能只是在这个钩子中更改一个视图属性,这将给出一个表达式已更改的警告。
如果您只想在您的showInputBox
中使用它,可以使用ChangeDetectorRef
constructor(readonly cd: ChangeDetectorRef) {}
showInputBox() {
this.isInputVisible = true;
this.cd.detectChanges();
doSomething($('#my-input');
}
或者像您已经使用过的那样使用setTimeout
,但是不使用100 use:
showInputBox() {
this.isInputVisible = true;
setTimeout(() => doSomething($('#my-input'));
}
这将确保它进入下一个更改检测循环。
https://stackoverflow.com/questions/52222540
复制相似问题