首页 > 解决方案 > 为什么没有为 Angular 8.0 发出我的点击事件?

问题描述

我想从父组件监听子组件的点击事件,但该事件没有发送给父组件。

子组件:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html',
})
export class ChildComponent implements OnInit {
  @Output() click = new EventEmitter<string>();

  constructor() { }

  ngOnInit() {
  }

  onClick() {
    console.log('click');
    this.click.emit();
  }

}

子模板:

<label>
    <div (click)="onClick()"></div>
</label>

父组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent-component.component.html',
})
export class ParentComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

  onChildClicked() {
    console.log('Child Clicked!');
  }

}

父模板:

<input type="checkbox" ngModel (click)="onChildClicked()">
<child-component></child-component>

当我单击时,我在控制台中收到来自孩子的第一条消息,但我没有收到第二条消息,它告诉我没有发出事件。

标签: javascripthtmlangular

解决方案


在你发出的时候尝试一个值。

this.click.emit('text');

此外,您确实需要选择与 click 不同的名称,因为 click 输出可能与 ng click 冲突


推荐阅读