Home > Back-end >  angular material button not functioning
angular material button not functioning

Time:11-02

I have created a form with a submit button using mat-raised-button but it does nothing

I was expecting it to print something to console using the onSubmit() function in my TS file. I tried using a normal button but still not working. What am I doing wrong here.

HTML: `

<div >
  <form  (ngSubmit)="onSubmit()">
  <p> 
    <mat-form-field appearance="legacy">
      <mat-label>First name</mat-label>
      <input type="text" name= "firstname" matInput ngModel>
    </mat-form-field>
  </p>
  <p>
    <mat-form-field appearance="legacy">
      <mat-label>Last name</mat-label>
      <input type="text" name= "lastname" matInput ngModel>
    </mat-form-field>
  </p>
  <p>
    <mat-form-field appearance="legacy">
      <mat-label>Employee number</mat-label>
      <input type="text" name= "employeenumber" matInput ngModel>
    </mat-form-field>
  </p>
  <p>
    <mat-form-field appearance="legacy">
      <mat-label>Favorite Superhero</mat-label>
      <input type="text" name= "favoritesuperhero" matInput ngModel>
    </mat-form-field>
  </p>
  <p>
    <mat-form-field appearance="legacy">
      <mat-label>Email</mat-label>
      <input type="text" name= "email" matInput ngModel>
    </mat-form-field>
  </p>

  <a mat-raised-button type="submit" >Sign Up!</a>
  </form>
  
</div>

`

TS;

`

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

@Component({
  selector: 'app-signupform',
  templateUrl: './signupform.component.html',
  styleUrls: ['./signupform.component.scss']
})
export class SignupformComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }


  onSubmit(){
    console.log('Sign up complete')
    
  }

}

`

CodePudding user response:

You can't set a type="submit" for a tag . This is the reason your (ngSubmit is not working ). If you want to use ngSubmit() change your a tag to the button. Otherwise, use the (click) method to invoke a function.

CodePudding user response:

To handle an event from a button element, you just need to add (click) into your button. You can get more information here: https://angular.io/guide/event-binding

<a mat-raised-button type="submit"  (click)="onSubmit()">Sign Up!</a>
  • Related