自定义 Angular 组件上的 Nativescript(点击)事件

Nativescript (tap) event on a custom Angular component

我正在尝试在 nativescript 中的 custom Angular 组件上绑定一个(点击)事件。

我创建了一个名为 'ns-custom' 的自定义组件,并尝试将 (tap) 事件绑定到它。但是没用。

在我这样做的自定义组件中:

<StackLayout>
    <Label text="Title"></Label>
    <Label text="some text"></Label>
</StackLayout>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'ns-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent{

  constructor() { }
}

我在父元素中这样做:

<ns-custom (tap)="onCustomComponentClick()"></ns-custom>
    onCustomComponentClick() {
        console.log('custom-component was tapped');
    }

我希望在我点击自定义组件时触发 (tap) 事件,但它没有。我在纯 Angular 中构建了相同的结构,如果将其放入自定义组件中,(click) 事件会触发。

我尝试从自定义组件传播 (tap) 事件,如下所示,但随后它触发了两次(正如预期的那样,因为如果我不使用,tap 事件将传播到父组件 event.stopPropagation()):

<StackLayout (tap)="emitTap()">
    <Label text="Title"></Label>
    <Label text="some text"></Label>
</StackLayout>

@Component({
  selector: 'ns-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent{
   @Output() tap = new EventEmitter();

   emitTap() {
       this.tap.emit();
   }
}

然后在父组件上捕获事件:

<ns-custom (tap)="onCustomComponentClick()"></ns-custom>
    onCustomComponentClick() {
        console.log('custom-component was tapped');
    }

但是现在点击事件触发了两次。我可以通过将 EventEmitter 名称更改为 'tap' 以外的名称来解决它(例如 @Output() childTapped = new EventEmitter();<ns-custom (childTapped)="onCustomComponentClick()"></ns-custom>),或者在点击时传递 $event 对象然后使用 event.stopPropagation(),但这一点都不优雅。

知道如何优雅地解决这个简单的问题吗?

@mick-morely 在评论中基本上回答了这个问题,但我想我会写一个更具描述性的示例,以及为什么我认为这是一种有用的方法。

您基本上需要为自定义组件创建自定义事件。虽然不能 re-use tap 事件看起来很乏味,但它实际上可以提高您的代码质量,使其更具描述性。

所以如果我有一个自定义 HoleComponent 描述一个“洞”,它可以看起来像这样:

孔模板

<GridLayout rows="*" columns="*" (tap)="emitTap()">
    <Label row="0" text="A very deep hole"></Label>
</GridLayout>

孔码

@Output() holeTap = new EventEmitter();

emitTap() {
    this.holeTap.emit();
}

这个 Hole 组件可以被 parent 像这样使用:

Parent 模板

<Hole (holeTap)="onHoleTap()"></Hole>

明确命名事件实际上有助于使代码更具可读性恕我直言。它还迫使开发人员更多地考虑他们正在使用的域,如果您喜欢使用 DDD,这有助于符合无处不在的语言。