TypeError:将ngModel与环形材料一起使用时,无法读取未定义的属性'bookIsbn'

时间:2018-11-23 16:25:01

标签: angularjs-directive angular-material ng-modules

我经历了所有相关问题,但找不到任何正确答案。 在表单数据绑定中将[[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() {
      }

    }

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

library-item.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');
}

错误 Console error message

预先感谢您考虑我的问题。

1 个答案:

答案 0 :(得分:1)

在您的html中,您已经使用bookIsbn作为表单验证输入...但是您要做的是添加一个字符串作为bookIsbn并尝试读取属性... 检查角度验证以进行正确验证。 https://angular.io/guide/form-validation