对象在打字稿/角度中可能为“空”

时间:2021-07-19 19:05:06

标签: html angular typescript

过去几天我一直在学习 angular 和 typescript,但在我的 member-form.component.html 上调用 *ngIf 文本字段中的方法时,我遇到了一个无法真正修复的错误。 成员component.ts是:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { MemberService } from '../member.service';
import { Member } from '../member';
import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";

@Component({
  selector: 'app-member-form',
  templateUrl: './member-form.component.html',
  styleUrls: ['./member-form.component.css']
})
export class MemberFormComponent implements OnInit {
  registerForm: FormGroup
  //submitted = false;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private memberService: MemberService,
    private formBuilder: FormBuilder) {

    let formControls = {
      surname: new FormControl('', [
        Validators.required,
        Validators.pattern("[A-Za-z .'-]+"),
      ]),
      name: new FormControl('', [
        Validators.required,
        Validators.pattern("[A-Za-z .'-]+"),
      ]),
      email: new FormControl('', [
        Validators.required,
        Validators.email
      ]),
      password: new FormControl('', [
        Validators.required
      ]),
      password2: new FormControl('', [
        Validators.required,
      ]),
      phone: new FormControl('', [
        Validators.required,
        Validators.minLength(10),
        Validators.maxLength(10),
        Validators.pattern("[0-9]+")
      ]),
    }
      this.registerForm = this.formBuilder.group(formControls)

  }


  ngOnInit(): void {}

get name() { return this.registerForm.get('name') }
  get surname() { return this.registerForm.get('surname') }
  get phone() { return this.registerForm.get('phone') }
  get email() { return this.registerForm.get('email') }
  get password() { return this.registerForm.get('password') }
  get password2() { return this.registerForm.get('password2') }
  

public onSubmit(): void {
    this.memberService.registerMember(this.registerForm.value).subscribe(result => this.gotoMemberList());
  }

  public gotoMemberList() {
    this.router.navigate(['/members']);
  }
}

和 html 文件是:

<link rel="stylesheet" href="member-form.component.css">

<div class="card my-5">
  <div class="card-body">
    <form [formGroup]="registerForm"(ngSubmit)="onSubmit()"style="border: 2px solid #ccc">

        <h1>Sign Up</h1>
        <p>Please fill in this form to register</p>
        <hr>


        <div class="form-group">
          <label for="surname"><b>Surname</b></label>
            <input formControlName="surname"
                   id="surname"
                   type="text"
                   class="form-control"
                   placeholder="Enter your surname">
            <div *ngIf="surname.touched && surname.invalid">
              <small *ngIf="surname.errors.required" class="text-danger">Surname is required</small><br>
              <small *ngIf="surname.errors.pattern" class="text-danger">Invalid Surname</small><br>
            </div>
        </div>

        <div class="form-group">
          <label for="name"><b>Name</b></label>
            <input formControlName="name"
                   id="name"
                   type="text"
                   class="form-control"
                   placeholder="Enter your name">
            <div *ngIf="name.touched && name.invalid">
              <small *ngIf="name.errors.required" class="text-danger">Name is required</small><br>
              <small *ngIf="name.errors.pattern" class="text-danger">Invalid Name</small><br>
            </div>
        </div>


        <div class="form-group">
          <label for="email"><b>Email</b></label>
            <input formControlName="email"
                   id="email"
                   type="email"
                   class="form-control"
                   placeholder="Enter your email address">
            <div *ngIf="email.touched && email.invalid">
              <small *ngIf="email.errors.required" class="text-danger">Email is required</small><br>
              <small *ngIf="email.errors.pattern" class="text-danger">Invalid Email</small><br>
            </div>
        </div>


        <div class="form-group">
          <label for="password" class="control-label"><b>Password</b></label>
          <input formControlName="password"
                 id="password"
                 type="password"
                 class="form-control"
                 placeholder="Enter your password">
          <div *ngIf="password.touched && password.invalid">
            <small *ngIf="password.errors.required" class="text-danger">Password is required</small><br>
          </div>
        </div>


        <div class="form-group">
          <label for="password2"><b>Confirm password</b></label>
          <input formControlName="password2"
                 id="password2"
                 type="password"
                 class="form-control"
                 placeholder="Enter your password again">
          <div *ngIf="password2.touched && password2.invalid">
            <small *ngIf="password2.errors.required" class="text-danger">Password is required</small><br>
          </div>
          <div *ngIf="password2.valid && password2.value != password.value" class="text-danger">
            The passwords entered do not match
          </div>
      </div>


        <div class="form-group">
          <label for="phone"><b>Phone Number</b></label>
          <input formControlName="phone"
                 id="phone"
                 type="tel"
                 class="form-control"
                 placeholder="Enter your phone number">
          <div *ngIf="phone.touched && phone.invalid">
            <small *ngIf="phone.errors.required" class="text-danger">Phone is required<br></small>
            <small *ngIf="phone.errors.pattern" class="text-danger">Invalid Phone<br></small>
            <small *ngIf="phone.errors.minlength" class="text-danger">Phone must be 10 characters </small>
<!--            <small *ngIf="phone.errors.maxlength" class="text-danger">Phone must contain a maximum of 13 characters</small>-->
          </div>
        </div>

        <br>
        <div class="form-group">
          <button type="submit" class="btn btn-primary" [disabled]="registerForm.invalid || password.value != password2.value">Sign Up</button>
        </div>
    </form>
  </div>
</div>

基本上,我收到一条错误消息,指出“在我的 html 文件的 *ngIf 字段中,每个 .errors、.pattern、.required、.invalid、.touched 的对象可能为 'null'。 有人知道这里可能出了什么问题吗?

2 个答案:

答案 0 :(得分:0)

原因是 strictNullChecks 是默认开启的。

您可以在 tsconfig.json 中关闭它但不建议这样做

  "angularCompilerOptions": {
    "strictNullChecks": false,
    ...
  }

正如@CherryDT 所评论的,您可以将 ?. 添加到每个引用

或者在这种情况下添加为首先检查对象本身surname

<div *ngIf="surname && surname.touched && surname.invalid">

更多信息:https://blog.angular.io/angular-cli-strict-mode-c94ba5965f63

?. 被称为“可选链”,您可以阅读有关它的更多信息here

答案 1 :(得分:-2)

我知道你不能像这样使用它“name.touched && name.invalid”, 您需要调用表单的方法。 check it out demo angular reactive forms