La Reyna
La Reyna

Reputation: 138

How to create a custom event in Angular, within same component?

Is it possible to create a custom event in Angular, within same component?

I am trying to create a custom click event in "app.component.html" file:

<li (customClick) = "cClick($event)"> Test </li>

and then in the app.component.ts file:

cClick(e){ (alert("custom event clicked!"))}

How to achieve this calling within same component? Please help :)

Upvotes: 1

Views: 2329

Answers (2)

vaira
vaira

Reputation: 2270

<li (customClick) = "cClick($event)"> Test </li>

You have to create a directive, where you can listen to whatever event you want and trigger them in your custom output emitters

Angular2 Directive to modify click handling

Upvotes: 1

Chintan Vasoya
Chintan Vasoya

Reputation: 165

footer component

  @Component({
         selector: 'a-footer',
         template: `
           <div>{{footerText}}</div>
           <button ion-button (click)="doIt()">Footer Button</button>
          `
        })
        export class AFooterComponent {
          @Input() footerText:string
          @Output() footerClicked = new EventEmitter()
          
          doIt() {
            this.footerClicked.emit({value:this.footerText})
          }
        }

home.page component create the event handler to be passed into footer component doFooterClicked

@Component({
  selector: 'page-home',
  templateUrl: 'app/home.page.html'
})
export class HomePage {

  appName = 'Ionic App';
  userCourse =[]

  constructor(private navController: NavController) {
    
    this.userCourse = [{CourseName:"course one"},{CourseName:"course two"}]
  }
  
  edit4(_someStuff) {
    
  }
  doFooterClicked(_event) {
    console.log(_event)
    alert("footer clicked "+ _event.value)
  }

}

in the home.page html somewhere you create the component element

<a-footer [footerText]="'someText'"
          (footerClicked)="doFooterClicked($event)">
</a-footer>`

Upvotes: 2

Related Questions