gpt4 book ai didi

javascript - Angular Reactive 表单渲染问题破坏了表单

转载 作者:行者123 更新时间:2023-12-03 01:13:18 25 4
gpt4 key购买 nike

所以我在 Angular react 形式方面遇到了一个非常奇怪的问题。我问了我的教练,他不明白,所以我只有一个地方希望得到一些帮助。它在这里。所以我使用 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>

然后继续,请忽略 Accordion 部分。那么我的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".

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

最佳答案

我用 *ngIf="form"解决,这样只有当表单准备好时才会呈现表单标签。

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

关于javascript - Angular Reactive 表单渲染问题破坏了表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52128674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com