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

时间:2019-09-28 22:53:14

标签: nativescript angular2-nativescript

我正在尝试在本机脚本的自定义 Angular组件上绑定一个(tap)事件。

我创建了一个名为“ 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)事件,但随后触发了两次(如预期的那样,因为如果我不使用event.stopPropagation(),tap事件将传播到父组件) :

<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对象然后使用{{1} },但这一点都不优雅。

有什么想法可以用一种优雅的方式解决这个简单的问题吗?

1 个答案:

答案 0 :(得分:2)

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

基本上,您需要为自定义组件创建一个自定义事件。虽然无法重用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组件可以被这样的父母使用:

父模板

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

使事件显式命名实际上有助于使代码更具可读性。它还迫使开发人员更多地考虑与他们一起使用的Domain,如果您与DDD一起工作,则有助于符合无处不在的语言。