Angular Reactive表单渲染问题打破了表单

时间:2018-09-01 13:42:56

标签: javascript angular

所以我对Angular反应形式有一个很奇怪的问题。我问我的老师,他无法弄清楚,所以我只有一个地方希望得到帮助。它在这里。 因此,我使用的是Angular表单,signup.component.html代码段为:

<form [formGroup]="form" (submit)="onSaveUser()" *ngIf="!isLoading">

  <mat-accordion class="accordion-headers-align">
    <mat-expansion-panel [expanded]="1">
      <mat-expansion-panel-header>
        <mat-panel-title>Personal data</mat-panel-title>
        <mat-panel-description>Type your personal details</mat-panel-description>
      </mat-expansion-panel-header>

      <mat-form-field>
        <input matInput type="text" formControlName="name" placeholder="Name">
        <mat-error *ngIf="form.get('name').invalid">Please enter your name</mat-error>
      </mat-form-field>

      <mat-form-field>
        <input matInput type="date" formControlName="dob" placeholder="DD/MM/YYYY">
        <mat-error *ngIf="form.get('dob').invalid">Please enter your valid date of birth in form of DD/MM/YYYY</mat-error>
      </mat-form-field>

继续这样,请忽略手风琴部分。 然后我的signup.component.ts文件是:

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

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

  isLoading = false;
  form: FormGroup;
  imagePreview: string;

  constructor(public userService: UsersService, public route: ActivatedRoute) { }

  ngOnInit() {
    this.form = new FormGroup({
      name: new FormControl(null, {validators: [
        Validators.required,
        Validators.minLength(3),
        // tslint:disable-next-line:quotemark
        Validators.pattern(some regex not of concern)
      ]}),
      dob: new FormControl(null, {validators: [
        Validators.required,
        // tslint:disable-next-line:max-line-length quotemark
        Validators.pattern(some regex not of concern)
      ]}),

继续这样,没什么特别的。仅尝试映射表单字段。所以表单呈现如下:我在控制台中遇到的错误是:

ERROR TypeError: "this.form is undefined, can't access property "get" of it".

ERROR Error: "formGroup expects a FormGroup instance. Please pass one in.

ERROR TypeError: "_co.form is undefined, can't access property "get" of it".

我不知道出了什么问题,我检查了文档和所有内容,没有帮助。我想这可能是个错误,所以想确定一下。

1 个答案:

答案 0 :(得分:1)

我使用* ngIf =“ form”进行解析,这样,只有在表单准备就绪时,表单标记才会呈现。

<form [formGroup]="form" (submit)="onSaveUser()" *ngIf="form">