首页 > 解决方案 > 如何知道哪个孩子在Angular上使用@Output向父母发送事件

问题描述

尝试在使用 Angular (11) 和 NativeScript 的事件中获取“当前本地元素”时,我失去了理智……

我有一个包含多个块(块组件)的容器(主组件)。每个组件都有一个“onPan”事件管理,这个事件用@Output 转发让父知道。然后,父母(家)听这个平移事件......

所有这些都有效。但是当父母收到事件时,我无法检查哪个元素正在移动。我的意思是,“PanGestureEventData”带有一个原生的“view”属性,但我无法从这个事件中检索到 Angular“nativeElement”。

我试图在父模板侦听器上添加“this”,但我不知道它是哪个对象:x

您是否有任何解决方案可以在父级上检索“块”QueryList 中的哪个元素当前正在发送事件?

这是一般情况,它可以是任何不携带当前目标的自定义事件,从子级发送到其父级:)

谢谢 !

我的片段:

home.component.html

<GridLayout #refGrid columns="*,*,*,*,*,*" rows="*,*,*,*,*,*" width="100%">
  <ns-block #block col="1" row="1" (moveEvent)="onMove(this, $event)"></ns-block>
  <ns-block #block col="2" row="1" (moveEvent)="onMove(this, $event)"></ns-block>
  <ns-block #block col="3" row="1" (moveEvent)="onMove(this, $event)"></ns-block>
  <ns-block #block col="1" row="2" (moveEvent)="onMove(this, $event)"></ns-block>
</GridLayout>

home.component.ts

import {Component, ElementRef, QueryList, ViewChildren} from "@angular/core";
import {PanGestureEventData} from "@nativescript/core";
import {BlockComponent} from "../component/block/block.component";

@Component({
  selector: "Home",
  templateUrl: "./home.component.html"
})
export class HomeComponent {
  @ViewChildren(BlockComponent, { read: ElementRef }) blocks!: QueryList<ElementRef>;

  onMove(element, args: PanGestureEventData): void {
    console.log("move", element);
  }
}

block.component.tns.html

<Image (pan)="onPan($event)"
   src="https://images.pexels.com/photos/102104/pexels-photo-102104.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"></Image>

块.component.ts

import {Component, Output, EventEmitter} from '@angular/core';
import {PanGestureEventData} from "@nativescript/core";

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

    @Output() moveEvent = new EventEmitter<PanGestureEventData>();

    onPan(args: PanGestureEventData): void {
        this.moveEvent.emit(args);
    }
}

标签: angulareventsnativescript

解决方案


您不能为每个子组件提供不同的模板引用变量并将其发送到事件处理程序吗?

home.component.html

<GridLayout #refGrid columns="*,*,*,*,*,*" rows="*,*,*,*,*,*" width="100%">
  <ns-block #block1 col="1" row="1" (moveEvent)="onMove(block1, $event)"></ns-block>
  <ns-block #block2 col="2" row="1" (moveEvent)="onMove(block2, $event)"></ns-block>
  <ns-block #block3 col="3" row="1" (moveEvent)="onMove(block3, $event)"></ns-block>
  <ns-block #block4 col="1" row="2" (moveEvent)="onMove(block4, $event)"></ns-block>
</GridLayout>

home.component.ts

onMove(element, args: PanGestureEventData): void {
  console.log("move", element);
}

更新:动态生成<ns-block>

在使用循环动态生成标记的情况下,它变得更加简单,因为您不必单独命名标签。您可以使用它的模板 ref 变量将当前元素直接发送到处理程序。

<GridLayout #refGrid columns="*,*,*,*,*,*" rows="*,*,*,*,*,*" width="100%">
  <ns-block *ngFor="let item of someArray" #block col="1" row="1" (moveEvent)="onMove(block, $event)"></ns-block>
</GridLayout>

推荐阅读