【问题标题】:How call jQuery method in component?如何在组件中调用 jQuery 方法?
【发布时间】: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 是个不错的主意,但这不取决于我

标签: jquery angular


【解决方案1】:

我建议

  1. 导入元素引用

    从 @angular/core 导入 { ElementRef }

  2. 将它注入到你的组件中

    构造函数(私有 elementRef ElementRef){}

  3. 在 ngOnInit 内部

    让元素 = $(this.elementRef.nativeElement).find('#def');

我没有测试,但试一试!

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 2018-08-21
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 2017-02-27
    • 2015-01-10
    相关资源
    最近更新 更多