在材料表单字段中输入输入时出错

时间:2018-01-17 01:37:10

标签: angular angular2-forms

我正在以角度2开发一个简单的表单。我有一个包含该表单的AddProfessorComponent

import { Component, OnInit } from '@angular/core';

import { Professor } from '../professors.model';

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

  siap: any;
  name: any;
  nickname: any;

  professor = new Professor(123, "rola", "ro");

  constructor() { }

  ngOnInit() {  }

  onSubmit() { }
}

这是该组件的html模板:

<mat-card>
  <mat-card-title>Cadastrar professor</mat-card-title>

  <form (ngSubmit)="onSubmit()" #addProfessorForm="ngForm" >
    <div class="example-container">
      <mat-form-field type="text">
        <input matInput #siap (ngModel)="siap" maxLength="7" placeholder="SIAP" name="siap" pattern="[0-9]{7}" required>
        <mat-hint align="end">{{siap.value?.length || 0}}/7</mat-hint>
      </mat-form-field>

      <mat-form-field type="text">
        <input matInput [(ngModel)]="name" placeholder="nome" name="name" required>
      </mat-form-field>

      <mat-form-field type="text">
        <input matInput #nickname (ngModel)="nickname" maxLength="12" placeholder="apelido" name="nickname" required>
        <mat-hint align="end">{{nickname.value?.length || 0}}/12</mat-hint>
      </mat-form-field>

      <button type="submit" mat-button class="button" color="primary" [disabled]="!addProfessorForm.form.valid">SALVAR</button>
    </div> 
  </form>

</mat-card>

当我在输入字段中插入任​​何信息时,我收到一条错误消息:

  

AddProfessorComponent.html:13 ERROR TypeError:   jit_nodeValue_9(...)。$ any不是函数
      at Object.eval [as handleEvent](ng:///ProfessorsModule/AddProfessorComponent.ngfactory.js:151:46)

以下是发生错误的image

有人知道我该如何解决这个问题?我到处搜寻。

1 个答案:

答案 0 :(得分:1)

请尝试以下语法:

<form #addProfessorForm="ngForm" (ngSubmit)="onSubmit(addProfessorForm)">

  <mat-form-field type="text">
    <input matInput #siap="ngModel" ngModel maxLength="7" placeholder="SIAP" name="siap" pattern="[0-9]{7}" required>
    <mat-hint align="end">{{siap.value?.length || 0}}/7</mat-hint>
  </mat-form-field>

  <button mat-button class="button" color="primary [disabled]="!addProfessorForm.form.valid"> SALVAR </button>
</form>

ngForm指令的情况下,您不需要在Component上拥有siap。它是addProfessorForm的一部分,因此可以提交为

onSubmit(addProfessorForm: NgForm) {
  addProfessorForm.siap;
}