【问题标题】:Angular Material Button and RxJS fromEvent function - there is no nativeElement property but just _nativeElement propertyAngular Material Button 和 RxJS fromEvent 函数 - 没有 nativeElement 属性,只有 _nativeElement 属性
【发布时间】:2019-01-20 21:43:56
【问题描述】:

我有一个 Angular 组件,在它的模板中我放置了一个 Angular Material 按钮,例如 <button #myButton mat-button></button>

现在我想做的是在我的代码中获取这个按钮,生成一个 Observable,当按钮被点击时发出,然后愉快地用这个 Observable 做我需要做的任何事情。

第一件事:我使用@ViewChild 和下面的代码来控制按钮

@ViewChild('myButton') myButton: MatButton;

我将变量的类型指定为MatButton,因为它实际上就是那种类型。

最后是我的问题。我想使用我常用的方法,即在ngAfterViewInit 方法中使用fromEvent(this.myButton.elementRef.nativeElement, 'click')。不幸的是,我收到错误Invalid event target。稍微挖掘一下,我发现MatButton 没有属性elementRef,但它有一个名为_elementRef 的属性。从开头的下划线看,这听起来像是一个私有属性,但我没有找到更好的方法来创建一个从 MatButton 指令开始并使用 RxJS 的 fromEvent 函数的 Observable。

任何建议都将不胜感激。

【问题讨论】:

    标签: angular rxjs angular-material


    【解决方案1】:

    您可以使用ViewChildread 选项访问按钮的ElementRef

    @ViewChild("myButton", { read: ElementRef }) myButtonRef: ElementRef;
    
    ngOnInit() {
      console.log(this.myButtonRef.nativeElement);
      ...
    }
    

    有关演示,请参阅this stackblitz,有关ViewChild 的更多信息,请参阅this article

    【讨论】:

    • 请注意,在 ng8 ViewChild 中也需要设置静态选项@ViewChild('myButton', {read: ElementRef, static: false})
    【解决方案2】:

    一些(不确定是否全部)Angular Material 组件公开了 EventEmitter 可观察对象,您可以直接订阅这些可观察对象,而无需使用 fromEvent

    例如,对于MatSlideToggle 组件,您可以这样写:

    @ViewChild('myToggle', { static: true }) myToggle: MatSlideToggle;
    

    然后在你的ngAfterViewInit():

    this.myToggle.change.subscribe((event: MatSlideToggleChange) => {
        ...
    })
    

    我假设您示例中的单击事件也被 MatButton 公开,但我没有尝试。

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 2018-12-09
      • 1970-01-01
      • 2018-03-10
      • 2020-04-01
      • 2021-07-15
      • 2019-10-23
      • 2017-03-17
      • 2021-02-15
      相关资源
      最近更新 更多