Javascript 类型错误:无法在 setUpControl 的字符串 '[email protected]' 上创建属性 'validator'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43603543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:01:30  来源:igfitidea点击:

TypeError: Cannot create property 'validator' on string '[email protected]' at setUpControl

javascriptangularangular2-routingangular2-templateangular2-forms

提问by Gunjan Patel

I face issue in formGroup. First Based on URL I take some value and call to API for retrieve particular user-data for pre-field text.

我在formGroup. 首先基于 URL 我取一些值并调用 API 以检索预字段文本的特定用户数据。

register.html

注册.html

<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="form-horizontal">
    <div class="form-group row">
        <label for="inputEmail3" class="col-sm-4 ">Username</label>
        <div class="col-sm-8">
            <input [formControl]="email" type="text" class="form-control" id="inputEmail3" placeholder="Email Address" [readonly]="isReadOnly">
        </div>
    </div>
</form>

register.component.ts

注册.component.ts

import { Component } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { EmailValidator, EqualPasswordsValidator } from '../../theme/validators';

@Component({
  selector: 'register',
  templateUrl: './register.html',
})
export class Register {
  public form: FormGroup;
  public email: AbstractControl;
  public username: string;

  constructor(private registerService: RegisterService, fb: FormBuilder, private router: Router, private route: ActivatedRoute) {
    this.form = fb.group({
      'email': ['', Validators.compose([Validators.required])]
      .... etc..
    });

    this.email = this.form.controls['email'];

    this.registerService.getUser({ userId: "asdasd2123da2das" }).subscribe(posts => {
      if (posts) {
          var userObj = posts.json();
          console.log("userObj : ", userObj.data);
          if (userObj.data && userObj.data[0].email) {
            this.email = this.username = userObj.data[0].email;  // ouput : [email protected]
            this.isReadOnly = true;
            this.router.navigateByUrl('/register');
          } else {
            alert("You are Not Autorize to access this Page");
            this.router.navigateByUrl('/login');
          }
        }
    });

  }
}

Error Details :

错误详情 :

TypeError: Cannot create property 'validator' on string '[email protected]'
    at setUpControl (http://localhost:3004/vendor.dll.js:9739:23)
    at FormControlDirective.ngOnChanges (http://localhost:3004/vendor.dll.js:44196:89)
    at Wrapper_FormControlDirective.ngDoCheck (/ReactiveFormsModule/FormControlDirective/wrapper.ngfactory.js:50:18)

回答by sainu

<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="form-horizontal">
        <div class="form-group row">
            <label for="inputEmail3" class="col-sm-4 ">Username</label>
            <div class="col-sm-8">
                <input formControlName="email" type="text" class="form-control" id="inputEmail3" placeholder="Email Address" [readonly]="isReadOnly">
            </div>
        </div>
</form>

please try like this change [formControl]to formControlName.

请尝试将此更改[formControl]formControlName.

And to set the output to the input field please do the following, point the line this.form.patchValue

并将输出设置为输入字段,请执行以下操作,指向线 this.form.patchValue

import { Component } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { EmailValidator, EqualPasswordsValidator } from '../../theme/validators';

@Component({
  selector: 'register',
  templateUrl: './register.html',
})
export class Register {
  public form: FormGroup;
  public email: AbstractControl;
  public username: string;

  constructor(private registerService: RegisterService, fb: FormBuilder, private router: Router, private route: ActivatedRoute) {
    this.form = fb.group({
      'email': ['', Validators.compose([Validators.required])]
      .... etc..
    });

    this.email = this.form.controls['email'];

    this.registerService.getUser({ userId: "asdasd2123da2das" }).subscribe(posts => {
      if (posts) {
          var userObj = posts.json();
          console.log("userObj : ", userObj.data);
          if (userObj.data && userObj.data[0].email) {
            this.email = this.username = userObj.data[0].email;  // ouput : [email protected]
            this.form.patchValue({
                email : this.email
             });

            this.isReadOnly = true;
            this.router.navigateByUrl('/register');
          } else {
            alert("You are Not Autorize to access this Page");
            this.router.navigateByUrl('/login');
          }
        }
    });

回答by Viswa

I missed the square brackets in formGroup in markup as below

我错过了标记中 formGroup 中的方括号,如下所示

<form formGroup="form">
</form>

and it throws similar error as

它抛出类似的错误

ERROR TypeError: Cannot create property 'validator' on string 'form'

错误类型错误:无法在字符串 'form' 上创建属性 'validator'

Once the square brackets added in formGroup (see below), the error disappears

一旦在formGroup中添加方括号(见下文),错误就会消失

<form [formGroup]="form">....</form>

回答by Vinayak Shedgeri

For complete information about each kind of form, see Reactive Forms and Template-driven Forms from the https://angular.io/guide/forms-overviewwebsite. you are missing actual syntax for Grouping form controls and Registering the control in the template.both are valid in different case

有关每种表单的完整信息,请参阅https://angular.io/guide/forms-overview网站上的Reactive Forms 和 Template-driven Forms 。您缺少分组表单控件和在模板中注册控件的实际语法。两者在不同情况下都有效

<input type="text" [formControl]="name">
<input type="text" formControlName="firstName">