即使在角度6的字段中输入值,反应形式也无效

时间:2019-03-13 06:58:10

标签: validation angular6 angular-reactive-forms

我有登录响应式表单,并向表单字段添加了验证。 用户在表单字段中输入值后,应在我显示form.value时更新屏幕上的表单值,并且还应显示表单状态。表单值和状态均未更改。 什么都没发生。

html

<div class="jumbotron">
 <div class="container">
  <div class="row">
   <div class="col-md-6 offset-md-3">
    <h2>Login</h2>
    <form class='form' [formGroup]='loginForm' (ngSubmit)='onSubmit()' novalidate>
      <div class="form-group">
          <label for="username">Username</label>
          <input type="text" class="form-control" id="username" placeholder="Username"/>
          <div *ngIf="f.username.touched && f.username.errors" class="invalid-feedback">
              <div *ngIf="f.username.errors.required">Username is required</div>
          </div>
      </div>
      <div class="form-group">
          <label for="password">Password</label>
          <input type="password" class="form-control" id="password" placeholder="Password"/>
          <div *ngIf="f.password.touched && f.password.errors" class="invalid-feedback">
              <div *ngIf="f.password.errors.required">Password is required</div>
          </div>
      </div>
      <div class="form-group">
          <label><input type="checkbox"> Remember me</label>
      </div>
      <div class="form-group">
        <button [disabled]="loginForm.invalid" class="btn btn-primary">Login</button>
           </div>
          </form>
          <p>Form value: {{loginForm.value | json}}</p>
          <p>Form value: {{loginForm.status | json}}</p>
        </div>
      </div>
     </div>
   </div>

ts文件

import { ObjectMethod } from '@babel/types/lib';
import { AuthService } from './../auth.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';

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

 loginForm: FormGroup;
 returnUrl: string;

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

 ngOnInit() {
  this.loginForm = this.formBuilder.group({
        username: ['', [ Validators.required]],
        password: ['', [ Validators.required]]
    });
}
//convenience getter for easy access to form fields
get f() {
  return this.loginForm.controls;
}

onSubmit() {
console.log(this.loginForm.value);
 /*Object.keys(this.loginForm.value).map(e => {
  console.log(">>>>>>>",this.loginForm.value[e]);
 });*/

 this.authService.getUserDetails();
}

} 由于表单无效,因此也未启用登录按钮。 请帮助我解决这个问题。

0 个答案:

没有答案