【问题标题】:jquery : access element inside an angular *ngIf directivejquery:访问角度 *ngIf 指令内的元素
【发布时间】: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


【解决方案1】:

让我们忽略您在 angular 中使用 jquery 并使用 ID 来引用元素的部分;)无论如何,在您的第二个代码示例中,您使用的是 ngOnInit。在这个钩子中,还没有可用的模板元素。为此,您必须使用 ngAfterViewInit 钩子。

但你不能只更改该钩子内的视图属性,这将给出一个表达式已更改警告。

如果您只想在您的showInputBox 中使用它,您可以使用ChangeDetectorRef

constructor(readonly cd: ChangeDetectorRef) {}

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

或者像您已经使用的那样使用setTimeout,但没有 100 毫秒:

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

这确保它进入下一个变化检测循环

【讨论】:

  • 虽然答案有效,但我认为您应该在第一段上进行更多开发,并给他一个 Angular 解决方案而不是 JQuery 解决方案!
  • @trichetriche 我试过了,但doSomething 需要一个jQuery 对象,并且可能从那里加载一个库方法。我不能在那里重写 angular .. 但我同意你的观点,angular 内没有 jquery :)
猜你喜欢
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2015-07-28
  • 1970-01-01
相关资源
最近更新 更多