How to call multiple methods on a button click using Angular 5?
Asked Answered
S

3

16

i am using angular 5 and facing a problem. i want to submit (click) event and call two or multiple method one bye one. Please give me idea or solution so that i can submit a (click) event and call two or multiple method.

such as

.html file

   <button (click)="abc(); bcde()"></button>

.ts file

  first method  
  abc(){}

  second method method
  bcde(){}

is this a right way to do this. Please suggest me and help me to solve this

Slusher answered 18/1, 2018 at 9:14 Comment(4)
What issue are you facing ? Whats the error ?Awaken
You can call other methods from abd() like this abc(){ this.bcde();this.cdef();}Lingerfelt
can you please tell me the correct way to call multiple method.. i am new in angular 5Slusher
I had this problem on rest api calls, they would not call in order till i found this article: https://mcmap.net/q/747357/-how-to-guarantee-sequential-order-with-angular-http-rest-api-in-for-loopWaverly
P
11
<button (click)="callall()"></button>

make one function and call all the function in that

function 1

abc(){}

function 2

bcde(){}

call both in common function

 callall(){

        this.abc()
        this.bcde() 
}
Patricia answered 18/1, 2018 at 9:19 Comment(3)
It's a use case that is best avoided raihan, as the others have already pointed out. Better to have a single method you call and from there call the other methods you want.Plotkin
why should this use case be avoided? It can happen that a click triggers two differ actions and it's not bad to make that explicit.Ondine
I agree that this is a bad practice! They should be called separately too avoid multiple code smells and pit falls.Amortizement
N
39

you can also do

<button (click)="[abc(), bcde()]"></button>
Needleful answered 11/1, 2019 at 22:9 Comment(0)
P
11
<button (click)="callall()"></button>

make one function and call all the function in that

function 1

abc(){}

function 2

bcde(){}

call both in common function

 callall(){

        this.abc()
        this.bcde() 
}
Patricia answered 18/1, 2018 at 9:19 Comment(3)
It's a use case that is best avoided raihan, as the others have already pointed out. Better to have a single method you call and from there call the other methods you want.Plotkin
why should this use case be avoided? It can happen that a click triggers two differ actions and it's not bad to make that explicit.Ondine
I agree that this is a bad practice! They should be called separately too avoid multiple code smells and pit falls.Amortizement
D
9

This is the correct way I guess. It is working for me.

<button (click)="abc(); bcde()"></button>
Diluvium answered 5/5, 2020 at 4:14 Comment(2)
I tried this approach in AngularDart and it did not work. I had to make a new function that calls the other two.Cristinacristine
oo waw that is a good input, good to know @PiDiluvium

© 2022 - 2024 — McMap. All rights reserved.