【发布时间】:2018-09-07 12:24:38
【问题描述】:
我想使用隐藏在 *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对象?
【问题讨论】:
-
我不认为在 Angular 应用程序中使用 jQuery 是一个好主意,您可以使用 Angular 完成大部分使用 jQuery 可以完成的事情。如果你想引用元素,你可以使用@ViewChild 装饰器:Angular 提供的angular.io/api/core/ViewChild。
-
ngIf is a directive,当您使用 ngIf 时,它将从 DOM 中添加和删除元素。所以需要一些时间来再次添加元素,为什么它与settimeout().一起工作如果你只想隐藏元素使用display : none风格,就像这样:[style.display]="isInputVisible ? 'block' : 'none'"而不是'*ngIf="isInputVisible"'在你的输入.
标签: javascript jquery angular