【发布时间】:2017-08-09 00:47:52
【问题描述】:
我尝试在自己的组件中调用 jQuery 方法,但在 HTML 渲染后无法调用此方法。我是这样尝试的:
declare var $: any;
@Component({
selector: 'some-component',
template: `
<div *ngFor="let id of fieldIds" class="form-field">
<input type="text" id="{{id}}" class="form-control"/>
</div>
`
})
export class SomeComponent implements OnInit, AfterViewInit, AfterViewChecked {
fieldIds: string[] = ['abc', 'def', 'ghi'];
constructor() {}
ngOnInit(): void {
console.log($("#def"));
//is undefined
}
ngAfterViewInit(): void {
console.log($("#def"));
//is undefined
}
ngAfterViewChecked(): void {
console.log($("#def"));
//exist, but method is called too many times
}
}
但只有在 HTML 渲染后执行的方法是 ngAfterViewChecked。它被调用了很多次,但我只能调用它一次。我怎样才能做到这一点?
【问题讨论】:
-
为什么需要这样使用JQuery?
-
我不需要,我必须。 :) 这不是一个确切的情况。我必须在表单的某些输入上使用 jQuery-UI datepicker(客户要求),但表单必须是动态的(技术要求)。我知道混合 jQuery 和 angular2 是个不错的主意,但这不取决于我