首页 > 解决方案 > 类型错误:使用带有环形材料的 ngModel 时无法读取未定义的属性“bookIsbn”

问题描述

我经历了所有相关的问题,但找不到任何正确的答案。在表单数据绑定中使用带有角度材料的 [(ngModel)] 时出现错误。

add-book.component.html

    <html>
<head>
  <title>
    Create Book
  </title>
</head>

<header>
  <h2 class="form_heading"> Create New Book </h2>
</header>

<body class="create_Book_Body">
<form name="createBookForm" #createBookForm="ngForm">

  {{libraryItemModel | json}}


  <mat-form-field class="form_Field">
    <input type="text" pattern="[0-9]*" minlength="5" maxlength="5" min="10000"  name="bookIsbn" #bookIsbn="ngModel" [(ngModel)]="libraryItemModel.bookIsbn" matInput
           placeholder="DVD ISBN NO" required>
    <div *ngIf="((bookIsbn.touched) && !(bookIsbn.valid))">
      <div *ngIf="bookIsbn.errors.required">
        <mat-error >
          This field is required/Invalid
        </mat-error>
      </div>

      <div *ngIf="bookIsbn.errors.minlength">
        <mat-error >
          ISBN should be of 5 characters
        </mat-error>
      </div>

      <div *ngIf="bookIsbn.errors.pattern">
        <mat-error >
          Invalid Pattern
        </mat-error>
      </div>
    </div>
  </mat-form-field>
</form>
</body>
</html>

add-book.component.ts

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


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

      onSubmit($event) : void {
        console.log(($event));
      }

      constructor() { }

      ngOnInit() {
      }

    }

这里我创建了一个类库项,其中创建了模型并将表单数据绑定到。

库项目.ts

export class LibraryItem {

  constructor(
    public bookIsbn : string

  ){}

}

app.component.ts

import { Component } from '@angular/core';
import {LibraryItem} from './library-item';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Lib_Manager';

  inputText : string = 'initial Value'

   libraryItemModel = new LibraryItem('12345');
}

错误 控制台错误信息

提前感谢您考虑我的问题。

标签: angularjs-directiveangular-materialng-modules

解决方案


在您的 html 中,您使用 bookIsbn 作为表单验证输入...但是您所做的是添加一个字符串作为 bookIsbn 并尝试读取属性...检查角度验证是否正确验证.. https://angular.io /指南/表单验证


推荐阅读