简体   繁体   English

角度2(单击)在组件标签上

[英]angular 2 (click) on component tag

I have two angular components. 我有两个angular分量。 The first component is a list with the tag <my-list-comp></my-list-comp> . 第一个组件是带有标签<my-list-comp></my-list-comp> My second component is a button with the tag <my-button-comp></my-button-comp> . 我的第二个组件是带有标签<my-button-comp></my-button-comp> In the template of my list component I'm using the button component with it's tag like this: 在我的列表组件的模板中,我正在使用带有如下标记的按钮组件:

template my-list-comp.html : 模板my-list-comp.html

<div class="list>
    <ul><!-- some stuff --></ul>
    <my-button-comp></my-button-comp>
</div>

template my-button-comp.html : 模板my-button-comp.html

<button routerLink="/goToOtherComponent">Click me!</button>

Now my question: Is it possible to use the (click) on the tag <my-button-comp></my-button-comp> to call a function from the controller in my-list-comp like this: 现在我的问题是:是否可以使用标签<my-button-comp></my-button-comp>上的(click)controller中调用my-list-compfunction ,如下所示:

template my-list-comp.html : 模板my-list-comp.html

<div class="list>
    <ul><!-- some stuff --></ul>
    <my-button-comp (click)="myFunction()"></my-button-comp>
</div>

controller my-list.comp.ts : 控制器my-list.comp.ts

myFunction() {
    console.log('hello world');
}

I've tried it like above, but it didn't work? 我已经像上面一样尝试过,但是没有用? Is this possible? 这可能吗? Didn't find anything about this topic. 找不到关于此主题的任何东西。

You would need to use an EventEmitter and the Output decorator like so: 您将需要使用EventEmitter和Output装饰器,如下所示:

my-button-comp.ts 我的按钮,comp.ts

import { EventEmitter } from '@angular/core';
@Output() onBtnClick = new EventEmitter<undefined>();

my-button-comp.html 我的按钮,comp.html

<button (click)="onBtnClick.emit()">Click me!</button>

my-list-comp.html 我的列表,comp.html

<div class="list>
    <ul><!-- some stuff --></ul>
    <my-button-comp (onBtnClick)="myFunction()"></my-button-comp>
</div>

With angular components, the (something) syntax refers to events from a child to a parent component (see here for the official docs) so what you are doing is invalid. 对于有角度的组件, (something)语法指的是从子组件到父组件的事件(请参阅此处以获取官方文档),因此您所做的是无效的。

If you want to trigger something from a child to a parent, the correct way of doing it is to send an event from the child and have the proper listener in place in the parent component. 如果要从子级触发事件到父级,则正确的方法是从子级发送事件,并在父级组件中放置适当的侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM