首页 > 解决方案 > 我使用角度模板驱动的形式创建简单的形式

问题描述

但我得到了这个错误,

对象可能为 'null <span *ngIf="name.errors.minlength">您必须输入至少 3 个字符

为什么我的错误对象始终为空,minlength 未存储在我的错误对象中这是什么原因?

我的 hero.ts 文件是,

export class Hero {

  constructor(
    public id: number,
    public name: string,
    public email: string
  ) {  }

}

我的 formone.component.ts 文件是,

import { Component, OnInit } from '@angular/core';
import {NgForm} from "@angular/forms";
import {Hero}  from "../../hero"



@Component({
  selector: 'app-formone',
  templateUrl: './formone.component.html',
  styleUrls: ['./formone.component.css']
})
export class FormoneComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }


  model = new Hero(1, 'chamara','chamara@gmail.com');

  submitted = false;

  onSubmit() { this.submitted = true; }

 
  get diagnostic() { return JSON.stringify(this.model); }


  


}

我的 formone.component.html 文件是,

<div class="container mt-3">


  <div class="row">

    <div class="col-md-2">



    </div>

    <div class="col-md-8">

      <h4>Template Driven Forms</h4>
      <form #formone="ngForm" (ngSubmit)="onSubmit()">

        {{diagnostic}}
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" id="name"
                 required
                 [(ngModel)]="model.name" name="name" #name="ngModel" minlength="3" #x>


        </div>



        <div *ngIf="!name.valid" class="alert alert-danger" >

          <span *ngIf="name.errors.minlength">You must enter atleast 3 characters</span>
          <span *ngIf="name.errors.required">This field required</span>

        </div>









        <div class="form-group">
          <label for="alterEgo">Email</label>
          <input type="email"  class="form-control" id="alterEgo"
                 [(ngModel)]="model.email" name="alterEgo">
        </div>

        <br>
        <button type="submit"   class="btn btn-primary" [disabled]="!formone.form.valid">Submit</button>




      </form>




    </div>


    <div class="col-md-2">



    </div>




  </div>







</div>

请帮我解决这个问题,

标签: htmlangulartypescript

解决方案


您的方法似乎很好(至少对我而言),您可能需要处理一些事情

从输入代码中删除额外的#X(这会通过误导性错误检查引起问题)并尝试name?.errors?.minlength在检查错误时添加交叉检查名称是否存在。

<input type="text" class="form-control" id="name" required
                [(ngModel)]="model.name" name="name" #name="ngModel" minlength="3">

<span *ngIf="name?.errors?.minlength">You must enter atleast 3 characters</span>

您可以在此处查看有关模板驱动的错误处理的更多信息:

快乐编码.. :)


推荐阅读