sTx
sTx

Reputation: 1261

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);
 }
}

Upvotes: 3

Views: 4325

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

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?

Upvotes: 2

Related Questions