简体   繁体   中英

angular 2 (click) on component tag

I have two angular components. The first component is a list with the tag <my-list-comp></my-list-comp> . My second component is a button with the tag <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 :

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

template 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:

template 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 :

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:

my-button-comp.ts

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

my-button-comp.html

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

my-list-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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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