繁体   English   中英

我无法以角电抗形式捕获输入字段的值

[英]I am not able to catch the value of the input field in a angular reactive form

我正在尝试验证Angular反应形式,在这里我试图捕获输入字段的值,如果未验证输入字段,我将显示消息

<span *ngIf="signupForm.control['fname'].haserror(required) && signForm.control['fname'].invalid &&  signForm.control['fname'].touched "> Enter your Name </span>

..但我遇到错误->

 ERROR TypeError: Cannot read property 'fname' of undefined

我正在填写表格的所有细节

html代码-

<form [formGroup]='signupForm' (ngSubmit)="PostData(signupForm)">
       <h2 class="text-center"> Registeration Form </h2>
      <br/>
      <div class="form-group">
       <input type="text" formControlName='fname'  placeholder="First Name">
       <span *ngIf="signupForm.control['fname'].haserror(required) && signForm.control['fname'].invalid &&  signForm.control['fname'].touched "> Enter your Name </span>
      </div>  

 <input type="submit" value="Post Data" [disabled]='!signupForm.valid'>
          </div>
          </form> 

ts文件代码->

export class ReactiveComponent implements OnInit {

  signupForm: FormGroup;
  FirstName: string = '';
  LastName: string = '';
  Eamil: string = '';
  Password: string = '';
  constructor(public frmbuilder: FormBuilder) { // formBuilder assign all the formcontrol to formgroup
    this.signupForm = frmbuilder.group({
    fname: ['',Validators.compose([Validators.required , Validators.minLength(4)])],  // FormControl  Used to bring input value to the ts file 
    lname: ['', Validators.required],
    Emailid: ['', [Validators.required , Validators.email]],
    userpassword: ['', Validators.required ]
});


   }

  ngOnInit() {
  }

  PostData(signupForm: any) {
    console.log(signupForm.controls);
    this.FirstName  = signupForm.controls.fname.value;
    this.LastName  = signupForm.controls.lname.value;
    this.Eamil  = signupForm.controls.Emailid.value;
    this.Password  = signupForm.controls.userpassword.value;

  }

它应该是,

hasError总是在camelCase中

<span *ngIf="signupForm.get('fname').hasError(required) && signupForm.get('fname').invalid &&  signupForm.get('fname').touched "> Enter your Name </span>

尝试

<span *ngIf="signupForm.controls['fname'].hasError('required')">Firstname is Required!! </span>

注意您调用fname控件的方式,请执行signupForm.controls而不是signupForm.control

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM