27 Mayıs 2016 Cuma

Tamam event bağladım ama parametrelerini almak istiyorum

Tamam biraz palazlandınız ve kendi component'ınızı yazmaya başladınız. EventEmitter konusunu da çözdünüz ama attığınız event'i dışardan alıp içinde gönderdiğiniz verileri kullanmak istiyorsunuz. Çok basit bileşenle başlayalım.

my-component.component.ts


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

@Component({
    selector: 'my-component',
    template: '<button (click)="onButtonClicked($event)">Tıklayıver!</button>'})
export class MyComponent {
    @Output customClick = new EventEmitter();

    onButtonClicked(event) {
        alert("clicked");

        this.customClick.emit({
           message: 'Selam!'        });
    }
}





sonra da hazırladığımız bileşeni app.component'a ekleyerek kullanalım.

app.component.html

<my-component (customClick)="onCustomClicked($event)"></my-component>

app.component.ts


import { Component, Input, Output, EventEmitter } from '@angular/core';
import { MyComponent } from "./my-component.component";

@Component({
    selector: 'my-app',
    templateUrl: './app/app.component.html',
    directives: [MyComponent]
})
export class AppComponent {
    constructor() {
        
    }
    
    onCustomClicked(event) {
        alert(event.message);
    }
}

Burada dikkat etmeniz gereken şey template html kodunda $event ve ts kodu içindeyse düz event kelimesinin kullanılması. Sonrasında zaten gönderilen event referansı bir object olduğu için json syntax'ı ile istediğiniz kadar bilgiyi içinde gönderebilirsiniz. Örnekteki "message" alanı gibi.

Hiç yorum yok:

Yorum Gönder