1

Tengo un formulario de login que tiene autenticacion basica con spring security, y me sale un error en el html. Este es mi html, estoy usando angular material:`

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()" >

  <div formGroupName="loginGroup">

    <div class="internal-form-container">
    <div> <!--USER NUMBER-->
      <mat-form-field class="input-full-width" appearance="outline">
        <mat-label> User Number</mat-label>
        <input matInput
               placeholder="User name"
               maxlength="100"
               formControlName="userName"
               [ngClass]="{ 'is-invalid': submitted && f.userName.errors}">
        <mat-error *ngIf="f.userName.error?.required"> Must be filled</mat-error>
      </mat-form-field>
    </div>

    <div><!--PASSWORD-->
      <mat-form-field class="input-full-width" appearance="outline">
        <mat-label>Password</mat-label>
        <input matInput
               [type]="hide ? 'password' : 'text'"
               placeholder="Password"
               maxlength="50"
               formControlName="password"
               [ngClass]="{'is-invalid': submitted && f.password.errors }">
        <mat-error *ngIf="loginForm.get('loginGroup.password').hasError('required')"> You must enter a password</mat-error>
      </mat-form-field>
    </div>
    </div>

    <div class="checkbox"><!-- check Box-->
      <label>
        <input type="checkbox"> Remember Password
      </label>
    </div>
  </div>

  <div class="button-container"> <!--BUTTONS-->
    <button class="btn rounded-btn button" >{{ 'Login' }}</button>
    <button class="btn rounded-btn button" routerLink="/">{{ 'Cancel' }}</button>
    <div> <!-- aqui va el error si no encuentra el usuario correcto-->
    </div>
  </div>
</form>

Este es el TS:

import { routerTransition } from '../../router.animations';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AuthService} from '../../shared/guard/auth.service';
import {first} from 'rxjs/operators';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
   animations: [routerTransition()]
})

export class LoginComponent implements OnInit {
 loginForm: FormGroup;

 hide = true;

 form: any = {};
 submitted = false;
 loading = false;
 returnUrl: String;
 errorMessage = '';

constructor(
    private translate: TranslateService,
    public router: Router,
    private route: ActivatedRoute,
    private formbuilder: FormBuilder,
    private authService: AuthService,
    ) {
        this.translate.addLangs(['en', 'fr', 'ur', 'es', 'it', 'fa', 'de', 'zh-CHS']);
        this.translate.setDefaultLang('en');
        const browserLang = this.translate.getBrowserLang();
        // this.translate.use(browserLang.match(/en|fr|ur|es|it|fa|de|zh-CHS/) ? browserLang : 'en');

        this.loginForm = this.formbuilder.group({
          loginGroup: this.formbuilder.group({
            userName: ['', Validators.required],
            password: ['', Validators.required],
          })
        });

        // reset logout status
        this.authService.logout();

        // gets return url from route parameters or default to '/'
        this.returnUrl = this.route.snapshot.queryParamMap['returnUrl'] || '/';
    }

ngOnInit() {}

onLoggedin() {
    localStorage.setItem('isLoggedin', 'true');
}

get f () { return this.loginForm.controls; }

onSubmit() {
  this.submitted = true;

  // stop here if the form is invalid
  if (this.loginForm.invalid) {
    return;
  }

  this.loading = true;
  this.authService.loginUp(this.f.userName.value, this.f.password.value)
    .pipe(first())
    .subscribe(
      data => {
        this.router.navigate([this.returnUrl]);
      },
      error1 => {
        this.errorMessage = error1;
        this.loading = false;
      }
    );

}

y este es el error que me muestra al correr:

introducir la descripción de la imagen aquí

si alguien conoce algun resultado le agradeceria mucho.

5
  • f.password no existe, ése es el problema el 17 feb. 2019 a las 16:57
  • 1
    en el metodo get estoy llamando: get f () {return this.loginForm.controls} el 18 feb. 2019 a las 18:42
  • Ops, es verdad... El problema es userName/userNumber el 18 feb. 2019 a las 20:03
  • Me sigue saliendo el mismo error bro el 18 feb. 2019 a las 20:43
  • Con el código que tienes no puedo reproducir el error, los imports no coinciden con las clases que estás usando, por ejemplo el 19 feb. 2019 a las 8:01

1 respuesta 1

1

Agrega el safe navegation a f.username, que al parecer f.username es indefinido al comienzo de la aplicación.

        <mat-error *ngIf="f.userName?.error?.required"> Must be filled</mat-error>

1
  • 1
    muchas gracias bro, me sirvio el 21 feb. 2019 a las 22:13

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.