【问题标题】:angular 5 form validation:角度 5 表单验证:
【发布时间】:2019-01-04 11:17:33
【问题描述】:

我的 angular 5 表单出现此错误:

ERROR TypeError: Cannot read property 'invalid' of undefined
    at Object.eval [as updateDirectives] (AccountPage.html:56)

name 变量上。

我正在使用 FormBuilder,如下所示。

好像我需要一个 getter 或者缺少声明?

控制器:

import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
...
export class AccountPage  implements OnInit {

    accountError: string;
    form: FormGroup;
...



 constructor(
        fb: FormBuilder,
        private navCtrl: NavController,
        private auth: AuthService,
        private afs: FirestoreService,
        private fcmProvider: FcmProvider,
    ) {

        console.log("%c constructor de account", "color: #bada55");
        this.form = fb.group({
            // name: ['', Validators.compose([Validators.required, Validators.minLength(2), ])],
            // firstname: ['', Validators.compose([Validators.required, Validators.minLength(2), ])],
            // add1: ['', Validators.compose([Validators.required, Validators.minLength(6), ])],
            // add2: ['', Validators.compose([])],
            // zip: ['', Validators.compose([Validators.required, Validators.minLength(5), NumberValidator.numeric, ])],
            // city: ['', Validators.compose([Validators.required, Validators.minLength(3), ])],
            // phone: ['', Validators.compose([Validators.required, Validators.minLength(10), ])],
            name: [null, [Validators.required]],
            firstname: [null, [Validators.required]],
            add1: [null, [Validators.required]],
            add2: '',
            zip: [null, [Validators.required]],
            city: [null, [Validators.required]],
            phone: [null, [Validators.required]],
        });

模板:

 <div *ngIf="auth.authenticated">
    <form (ngSubmit)="submitForm()" [formGroup]="form">
      <ion-list inset>

        <ion-item>
          <ion-input type="text" placeholder="Nom" formControlName="name"></ion-input>
        </ion-item>

        <div *ngIf="form.name.invalid && (form.name.dirty || form.name.touched)" class="text-danger">
          <div *ngIf="form.name.errors.required">
            Entrez votre nom
          </div>
          <div *ngIf="form.name.errors.minlength">
            2 caractères minimum
          </div>
        </div>

编辑 这似乎有效:

    <ion-item>
      <ion-input type="text" placeholder="Nom" name="name" formControlName="name"></ion-input>
    </ion-item>

    <div *ngIf="form.controls['name'].invalid && (form.controls['name'].dirty || form.controls['name'].touched)" class="text-danger">
      <div *ngIf="form.controls['name'].errors.required">
        Entrez votre nom
      </div>
      <div *ngIf="form.controls['name'].errors.minlength">
        2 caractères minimum
      </div>
    </div>

this.form = this.formBuilder.group({
        name: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(2), ]) ),
    });

但我不能避免繁重的语法:模板中的form.controls['name'] 吗?

【问题讨论】:

  • 是的,您需要 getter 直接在模板中使用它,或者您可以使用 [formControl] 而不是 PLUNKER 这里有类似的示例
  • 在你的插件中,而不是这个 ̀ this.usernameCtrl = this.formBuilder.control('username', Validators.required); this.myForm = this.formBuilder.group({ username: this.usernameCtrl, }); ` Angular 的文档表明应该可以这样做 ` this.myForm = this.formBuilder.group({ username: new FormControl('username', Validators.required); }); }` 不对?
  • 我用一个几乎可行的解决方案更新了我的问题

标签: angular forms validation


【解决方案1】:

如果您在ngOnInit 生命周期钩子中使用console.log(this.form),您可以看到this.form 对象不包含属性名称。 FormGroup 内的每个 control 都存储在对象的 controls 属性内。因此,您必须声明将指向 this.form.controls 的变量,或者您可以使用this.form.controls['name'].valid 来检查表单的有效性

【讨论】:

    【解决方案2】:

    尝试使用 form.controls['name'].invalid 检查模板中的有效性

    【讨论】:

      【解决方案3】:

      答案如下:

      模板:

         <ion-item>
            <ion-input type="text" placeholder="Nom" name="name" formControlName="name"></ion-input>
          </ion-item>
      
          <div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
            <div *ngIf="name.errors.required">
              Entrez votre nom
            </div>
            <div *ngIf="name.errors.minlength">
              2 caractères minimum
            </div>
          </div>
      

      控制器:

      import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
      
      export class AccountPage  implements OnInit {
      
          accountError: string;
          form: FormGroup;
          name: FormControl;
          firstname: FormControl;
          add1: FormControl;
          add2: FormControl;
          zip: FormControl;
          city: FormControl;
          phone: FormControl;
      
       constructor(
              private formBuilder: FormBuilder,
              private navCtrl: NavController,
              private auth: AuthService,
              private afs: FirestoreService,
              private fcmProvider: FcmProvider,
          ) {
              this.form = this.formBuilder.group({
                  name: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(2), ]) ),
                  firstname: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(2), ]) ),
                  add1: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(6), ]) ),
                  add2: '',
                  zip: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(5), NumberValidator.numeric, ]) ),
                  city: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(3), ]) ),
                  phone: new FormControl( null, Validators.compose([Validators.required, Validators.minLength(10), ]) ),
              });
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        • 2020-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        • 1970-01-01
        相关资源
        最近更新 更多