0

嗨,我是 Angular 11 的新手,谁能帮我解决这个错误 - 这是我的代码。

checkout.component.html

<h3>Checkout forms - Using Reactive forms</h3>
<div class="container">
    <form [formGroup]="checkoutForm" (ngSubmit)="postData();">
        <div class="form-group">
          <label for="exampleInputEmail1">Email address</label>
          <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" name="emailAddressField" formControlName="emailAddr">
          <span *ngIf="checkoutForm.get('emailAddr').hasError('required')">Enter email address</span>
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">Quantity</label>
          <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="passwordField" formControlName="quantity">
          <small id="emailHelp" class="form-text text-muted">Enter Quantity</small>
        </div>
        <div class="form-check">
          <input type="checkbox" class="form-check-input" id="exampleCheck1" name="termsField" formControlName="terms">
          <label class="form-check-label" for="exampleCheck1">Agree to Terms</label>
        </div>
        <br>
        <button type="submit" class="btn btn-primary" [disabled]="!checkoutForm.valid">Checkout</button>
    </form>
</div>

我在 <span *ngIf="checkoutForm.get('emailAddr').hasError('required')">输入电子邮件地址处收到错误

checkout.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder,Validators} from '@angular/forms';

@Component({
  selector: 'app-checkout',
  templateUrl: './checkout.component.html',
  styleUrls: ['./checkout.component.css']
})
export class CheckoutComponent implements OnInit {
  checkoutForm:FormGroup;
  
  constructor(private formBuilder:FormBuilder) {

     this.checkoutForm = formBuilder.group({
      emailAddr: ['',Validators.required],
      quantity: ['',Validators.required],
      terms: ['',Validators.requiredTrue]
    });
  

  }

  
  ngOnInit(): void {

  }

  postData(){
    console.log(this.checkoutForm);
  }
}
4

2 回答 2

0

而不是使用

<span *ngIf="checkoutForm.get('emailAddr').hasError('required')">Enter email address</span>

尝试

<span *ngIf="checkoutForm.get('emailAddr')?.hasError('required')">Enter email address</span>

我已经在我的电脑上测试了这段代码,也许它也可以帮助你解决编译错误。

于 2021-05-13T20:55:52.387 回答
0

您可以使用*ngIf="cadastroForm.get('username')?.errors">.

你必须使用?.

于 2021-12-08T20:45:31.433 回答