Search code examples
angularangular-materialangular7angular-forms

matInput value doesn't get updated


I have a form Input field for username and password like this,

 <mat-form-field class="mdb-form-field-modal form-adjustments">
    <input (keydown)="emailBtnFocus($event)" tabindex="0" matInput placeholder="username" formControlName="username">
        <mat-error *ngIf="username.hasError('email') && !username.hasError('required')">
        {{ signInEmailErrorText }}
        </mat-error>
    <mat-error *ngIf="username.hasError('required')">
        {{requiredError }}
    </mat-error>
</mat-form-field>

export class SignInComponent implements OnInit {
    signInForm: FormGroup;
  username = new FormControl('', [
    Validators.required, Validators.email
  ]);

  ngOnInit() {
    this.authState = this.store.select('auth');
    this.signInForm = new FormGroup({
      'username': this.username,
      'password': this.password,
      'staySignedIn': this.staySignedIn
    });

  }
  // Submit Logic.
  onSignInSubmit() {
    console.log('SignInForm:', this.signInForm);
   //logic for submit goes here
  }
}

When I click on Submit the value still remains as null and I am not sure why . Can someone help me figure this out ?


Solution

  • do this:

    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    export class SignInComponent implements OnInit {
    signInForm: FormGroup;
    constructor(private formBuilder: FormBuilder) {}
    
      ngOnInit() {
        this.authState = this.store.select('auth');
        this.signInForm = this.formBuilder.group({({
          'username': ['', [Validators.required, Validators.email]],
          'password': ['', Validators.required],
          'staySignedIn': ['']
        });
    
      }
      // Submit Logic.
      onSignInSubmit() {
        console.log('SignInForm:', this.signInForm);
       //logic for submit goes here
      }
    }