Home > Software design >  Angular button (onClick) event not working
Angular button (onClick) event not working

Time:10-06

I have a button that should call a function that logs the user out. For some reason, the event is not working at all. Here is the code: TS File:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder, private auth: AuthService) { }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      email: '',
      password: ''
    })
  }

  submit(){
    this.auth.tryLogin(this.form.getRawValue())
    .subscribe(res => {
      console.log(res);
    })
  }

  public logout(){
    console.log("logout")
    this.auth.tryLogout()
    .subscribe(res => {
      console.log(res);
    })
  }

  // public testJWT(){
  //   alert("asd")
  //   this.auth.testAuth()
  //   .subscribe(res => {
  //     console.log(res)
  //   })
  // }
}

And the HTML:

<form [formGroup]="form" (submit)="submit()">
    <h1>Anmelden</h1>
    <input formControlName="email" type="email" placeholder="Email Addresse" required> 
    <br>
    <input formControlName="password" type="password" placeholder="Passwort" required>
    <br>
    <button type="submit">Anmelden</button>
</form>

<button (onClick)='logout()'>log out</button>

I have no idea what I am doing wrong, I tried using this.logout(), I tried type="button" in the html, but nothing worked for me.

CodePudding user response:

It should be click and not onClick.

<button (click)='logout()'>log out</button>

Syntax reference:

syntax

You can refer to the official wiki https://angular.io/guide/event-binding for more info

CodePudding user response:

The event is "click". you are using onClick which is incorrect. Please change onclick to click and check.

<button (click)='logout()'>log out </button>

Reference: https://angular.io/guide/user-input#binding-to-user-input-events

  • Related