Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 listen to custom event inside component

What I intend to do is to create a custom event to which I'll listen inside the same component that is created;

events.component.ts

    @Component({
    moduleId: module.id.replace("/dist/", "/"),
    selector: 'event-bind-c',
    template:`
             <button (click)="onClicked()">Component click</button>
             <input (clicked)="showIt($event)" [placeholder]="emitted_val">
            `
})
export class EventBindingComponent implements OnInit {
    toggled_value:boolean = false;
    emitted_val:string;

    constructor() { }

    ngOnInit() { }

    @Output() clicked = new EventEmitter<string>();
    onClicked = () => {
        //alert("Inside of component");
        this.clicked.emit("It works!");
    }

    showIt = (event_val:string) => {
        alert("event_val:" + event_val);
        this.emitted_val = event_val;
    }
}

If I use it outside of the component(in parent) it works

app.component.ts

@Component({
  selector: 'my-app',
  template: '<event-bind-c (clicked) = "onParentClicked($event)"></event-bind-c>',
})
export class AppComponent  { 
 onParentClicked= (value:string) => {
   alert("Outside of component "+value);
 }
}
like image 988
sTx Avatar asked May 31 '26 21:05

sTx


1 Answers

That's not supported.

Only the parent component can bind to an event emitted by an @Output()

Why don't you just call this.showIt() instead of emitting an event?

like image 76
Günter Zöchbauer Avatar answered Jun 03 '26 12:06

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!