【问题标题】:Angular 8 :ERROR TypeError: Cannot read property 'invalid' of undefinedAngular 8:错误类型错误:无法读取未定义的属性“无效”
【发布时间】:2020-03-29 21:35:36
【问题描述】:

有人能解释一下这实际上意味着什么吗?我是 Angular 的新手,目前正在使用 Angular 8,这出现在我的控制台上。

ERROR TypeError: Cannot read property 'invalid' of undefined

at Object.eval [as updateDirectives] (RegisterComponent.html:10)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:45259)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44637)
at execComponentViewsAction (core.js:44565)
at checkAndUpdateView (core.js:44278)
at callViewAction (core.js:44637)
at execEmbeddedViewsAction (core.js:44594)
at checkAndUpdateView (core.js:44272)
at callViewAction (core.js:44637)

这是我的源代码,它暗示有错误的页面

register.component.ts

   import { authTkn } from './../shared/model/loginDetails';
   import { MahasiswaApiService } from './../shared/services/mahasiswa-api.service';
   import { Component, OnInit } from '@angular/core';
   import { Router, RouterModule } from '@angular/router';
   import { FormBuilder, FormGroup, Validators } from '@angular/forms';
   import { first } from 'rxjs/operators';
   import * as CryptoJS from 'crypto-js';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  public authTkn: authTkn = null;

  registerForm = this.fb.group({
    user_name: ['', Validators.required],
    fullname: ['', Validators.required],
    telepon: ['', Validators.required],
    email: ['', Validators.required],
    alamat: ['', Validators.required],
    birthdate: ['', Validators.required],
    foto_profil: ['', Validators.required],
    password: ['', Validators.required],
  });


constructor(private mahasiswaApi: MahasiswaApiService, private route: Router, private fb: FormBuilder) { }

ngOnInit() {
  }


onSubmit() {
    this.registerForm.controls.password.patchValue(
      CryptoJS.SHA512(this.registerForm.value.password).toString()
    );
    console.log(this.registerForm.value);
    this.mahasiswaApi.postUserRegister(this.registerForm.value).subscribe(
      res => {
        console.log(res);
        this.authTkn = res;
        console.log(this.authTkn);
        localStorage.setItem('token', this.authTkn.token);
        this.mahasiswaApi.getCurrentToken();
        this.route.navigate(['/home']);
        alert(this.authTkn.info);
      },
      error => {
        console.log(error);
        alert(error.error.message);
      }
    );
  }
}

register.component.html

<div class="login-form">
  <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
      <h2 class="text-center"> Register </h2>

      <!-- Register Username -->
      <div class="form-group">
          <label for="user_name"> Username </label>
          <input type="text" class="form-control" name="Username" formControlName="user_name" placeholder="text">
          <div class="alert alert-danger" *ngIf="user_name.invalid && user_name.dirty" @myInsertRemoveTrigger>Username Must Be filled</div>
      </div>

      <!-- Register Nama Lengkap -->
      <div class="form-group">
        <label for="nama lengkap"> Nama Lengkap </label>
        <input type="text" class="form-control" name="Nama Lengkap" formControlName="fullname" placeholder="text">
        <div class="alert alert-danger" *ngIf="fullname.invalid && fullname.dirty" @myInsertRemoveTrigger> Please fill your complete name here</div>
    </div>

      <!-- Register Nomor Telepon -->
      <div class="form-group">
        <label for="nomor_telepon"> Nomor Telepon </label>
        <input type="text" class="form-control" name="Nomor Telepon" formControlName="telepon" placeholder="text">
      </div>

    <!-- Register Email -->
    <div class="form-group">
      <label for="email"> Email </label>
      <input type="email" class="form-control" name="Email" formControlName="email" placeholder="email">
    </div>

    <!-- Register Tanggal Lahir -->
    <div class="form-group">
      <label for="Tanggal_lahir"> Tanggal Lahir </label>
      <input type="date" class="form-control" name="Tanggal Lahir" formControlName="birthdate" placeholder="date">
    </div>

    <!-- Register Foto -->
    <div class="form-group">
      <label for="Foto_Profil"> Foto Profil </label>
      <input type="file" class="form-control" name="Foto Profil" formControlName="foto_profil" placeholder="file">
    </div>

    <!-- Register Password -->
    <div class="form-group">
      <label for="Password"> Password </label>
      <input type="password" class="form-control" name="Password" formControlName="password" placeholder="password">
      <div class="alert alert-danger" *ngIf="password.invalid && password.dirty" @myInsertRemoveTrigger>Password Must Be filled</div>
  </div>


      <!-- Button shit -->
      <div class="form-group">
          <button type="submit" class="btn btn-primary btn-block" [disabled]="!registerForm.valid"> Register </button>
      </div>

      <div class="clearfix">
          <label class="pull-left checkbox-inline"><input type="checkbox" formControlName="remember_me"> Remember me</label>
      </div>
  </form>
</div>

也许我有一些变量定义问题,但我确实在我的 ts 的第一部分为我的表单定义了使用变量的数组。也许我确实丢了东西,那是什么?

【问题讨论】:

    标签: html angular typescript web angular8


    【解决方案1】:

    您需要像这样访问表单对象上的表单控件:registerForm.get('user_name').invalid 等等,对于每个属性(例如 dirty)和表单中的每个控件。

    另一种选择是在组件类中为每个表单控件创建一个 getter:

    get user_name() {
        return this.registerForm.get('user_name');
    

    然后你可以保持你的 HTML 为当前状态。

    如果您查看此处的示例:https://angular.io/guide/form-validation#built-in-validators 他们会说:

    此示例添加了一些 getter 方法。在响应式表单中,您始终可以通过其父组上的 get 方法访问任何表单控件,但有时将 getter 定义为模板的简写很有用。

    参考表单控件的 getter。

    【讨论】:

    • 所以我需要有自己的 *ngIf 函数来定义验证?
    • 为组件类中的每个表单字段添加 getter,然后您可以保持原样。
    • 脏验证部分怎么样,你有什么想法让它工作吗?它需要一些功能还是只导入一些库?
    • 为每个表单字段添加 getter 后,所有代码都应该可以工作
    【解决方案2】:

    HTML *ngIf 无法定位 user_name.invalid(与 fullname.invalid 相同),因为它们不是组件中包含的变量。您将它们列在 formGroup 中,但这与在类顶部声明 user_name 变量不同。

    要使用户名、全名和密码可用,您需要像这样声明它们:

    user_name: string;
    fullname: string;
    password: string;
    

    然后将它们填充到您的代码中。当您现在将基本相同的数据驻留在两个地方时,这可能会变得混乱。

    或者,您可以使用函数从 formGroup 返回控制值:

    getUserName() {
        return this.formGroup.controls['user_name'].value;
    } 
    

    但最主要的是,在 formGroup 中指定的控件不能像通过 this 访问的变量一样显示。

    【讨论】:

    • 我应该在哪里添加 user_name: string,.... 部分?是在某种 registerdetails.ts 上还是什么的?
    • 不,它只是在控制器代码的顶部,在构造函数之前。您通常会在同一位置定义任何其他变量。
    【解决方案3】:

    #fullname = "ngModel" 添加到您要引用的输入中。您用于验证的 div 不知道全名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2021-12-16
      • 2021-11-05
      • 1970-01-01
      • 2019-04-15
      • 2018-11-21
      • 2020-05-25
      相关资源
      最近更新 更多