【问题标题】:Angular blur input角度模糊输入
【发布时间】:2018-10-01 12:53:12
【问题描述】:

我想“模糊”(或取消焦点等)来自控制器的输入元素。

我参考了输入@ViewChild('searchInput') searchInput: ElementRef

这行得通:

this.searchInput.nativeElement.focus()

但这似乎不是:

this.searchInput.nativeElement.blur()

【问题讨论】:

  • 有什么原因不能在标记中附加模糊? <input (blur)="blurHandler()" />这是一个很好的参考链接:stackoverflow.com/questions/34918198/…
  • @Pearman 很好处理模糊事件,我其实想触发一个
  • 你能显示你调用this.searchInput.nativeElement.blur()的上下文吗?
  • 您的代码应该可以工作,只要在元素存在于 DOM 中时调用它。见this stackblitz
  • 如果您想创建一种可以在解决方案中的所有输入字段中使用的方式,您可以使用装饰器 @HostListener ('mouseout')。您可以在下面的Link 中看到更多相关信息! codecraft.tv/courses/angular/custom-directives/…

标签: javascript angular


【解决方案1】:

在 Angular 5+ 中,Renderer 已被弃用,并且 Renderer2 没有 invokeElementMethod,但您的示例应该可以工作。在没有看到更多代码的情况下,我唯一能想到的是您没有将模板引用添加到标记中的输入:

模板

<input #myInput id="example" name="example" formControlName="example ...>

控制器

@ViewChild('myInput') public myInput: ElementRef<HTMLElement>;

// ...

public onSubmit() {
  this.myInput.nativeElement.blur();
}

【讨论】:

    【解决方案2】:

    可以尝试使用Renderer,在你的组件中注入渲染器,当你想模糊时调用下面的代码

    this.renderer.invokeElementMethod(this.searchInput.nativeElement, 'blur', []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-23
      • 2023-03-27
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 2017-04-01
      • 2021-08-13
      • 1970-01-01
      相关资源
      最近更新 更多