简体   繁体   English

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

[英]Object is possibly 'null' in typescript/angular

I have been learning angular and typescript for the past couple of days and I've hit an error I can't really fix when calling methods in the *ngIf text field on my member-form.component.html.在过去的几天里,我一直在学习 angular 和 typescript,但在我的 member-form.component.html 上调用 *ngIf 文本字段中的方法时,我遇到了一个无法真正修复的错误。 The member-component.ts is:成员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']);
  }
}

and the html file is:和 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>

Basically, I'm getting an error saying "Object is possibly 'null' on every .errors, .pattern, .required, .invalid, .touched in the *ngIf fields of my html file. Anyone knows what could be going wrong here?基本上,我收到一条错误消息,说“在我的 html 文件的 *ngIf 字段中,每个 .errors、.pattern、.required、.invalid、.touched 的对象可能为 'null'。任何人都知道这里可能出了什么问题?

The reason is a strictNullChecks which is turned on by default.原因是默认情况下启用了strictNullChecks

You can turn it off in tsconfig.json but that is not advised您可以在tsconfig.json关闭它,但不建议这样做

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

as @CherryDT commented you can add ?.正如@CherryDT 评论的,您可以添加?. to each reference每个参考

or add as first check the object itself in this case surname或添加为首先检查对象本身在这种情况下surname

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

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

?. is called "optional chaining" and you can read more about it here称为“可选链接”,您可以在此处阅读有关它的更多信息

And as i know you can not use it like this "name.touched && name.invalid", You need to call method of the your form.据我所知,您不能像“name.touched && name.invalid”那样使用它,您需要调用表单的方法。 check it out demo angular reactive forms 看看演示角反应形式

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

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