Home > database >  How call a function in an subimit button
How call a function in an subimit button

Time:07-08

I have this function to hide and show a div

Aoba(){
    if(this.fill == false){
      return this.fill = true
    }else if(this.fill == true){
      return this.fill = false
    }
    return console.log(this.fill)
  }

and it's working in my filter button, but i need use it again when i click to filter but it´s a subimit button and the subimit dont work when i put the function there.

 <div >
   <button type="submit" (click)="Aoba()" >{{'Filtrar' | translate}}</button>
 </div>

CodePudding user response:

Use the onclick attribute to specify the function to be called

function HandleClick() {
  alert("I've been clicked");
}
<button onclick="HandleClick()">Click me!</button>

CodePudding user response:

HTML

<form [formGroup]="XXXXX" (ngSubmit)="onSubmit()">
 <button type="submit">Continuer</button>
</form>

TS

onSubmit(): {

}

CodePudding user response:

First off,

return this.fill = true

is the same as just

return;

since this.fill = true doesn't return a value. So I would leave out the return keyword.

Secondly, your console.log will not be hit because you're returning before you get to it, regardless of what this.fill is.

You also don't need that second if, since this.fill is boolean, if it's not true, it's false. No other options. If it's not specifically a boolean, then ignore this paragraph, although I strongly suggest you cast it to something specific.

Third, if the function returns false, I believe it will stop form submission. It may not work at all with a (click) handler. I can't remember and I don't have time to recreate your test case (use StackBlitz for that).

What I would do is use a Reactive Form, and submit it in code. https://angular.io/guide/reactive-forms

Hope that helps. :)

  • Related