gpt4 book ai didi

angular - 无法直接访问 FormControl 实例。无法读取未定义的属性 'invalid'

转载 作者:太空狗 更新时间:2023-10-29 17:01:54 24 4
gpt4 key购买 nike

无法像在 Angular 文档中那样访问它,所以必须先获取 FormGroup 实例并在其中找到 FormControl 实例。我想知道为什么?这个例子有效:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="myForm.controls.username.invalid" class="alert alert-danger">
username is required
</div>
</div>

虽然这会引发错误(它们之间的区别仅在 *ngIf 语句中):

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="username.invalid" class="alert alert-danger">
username is required
</div>
</div>

Cannot read property 'invalid' of undefined

表单.组件:

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

@Component({
selector: 'sign-up',
templateUrl: 'app/sign-up.component.html'
})

export class SignUpComponent {

myForm = new FormGroup({
username: new FormControl('username', Validators.required),
password: new FormControl('', Validators.required),
});
}

最佳答案

它会抛出错误,因为您没有名为 usernamepassword 的变量。

为了解决这个问题,您可以:

  1. 将控件存储在组件变量中:

TS:

@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
readonly usernameCtrl = this.formBuilder.control('username', Validators.required);
readonly passwordCtrl = this.formBuilder.control('', Validators.required);
readonly formGroup = this.formBuilder.group({
username: this.usernameCtrl,
password: this.passwordCtrl
});

HTML:

<div 
*ngIf="userNameCtrl.invalid" class="alert alert-danger"
>
username is required
</div>
  1. 使用AbstractControl#get捕获控制权:

HTML:

<div 
*ngIf="formGroup.get('username').invalid" class="alert alert-danger"
>
username is required
</div>
  1. 使用AbstractControl#hasError这样您就可以为每个现有的验证指定不同的消息:

HTML:

<div 
*ngIf="formGroup.hasError('required', 'username')" class="alert alert-danger"
>
username is required
</div>

DEMO

关于angular - 无法直接访问 FormControl 实例。无法读取未定义的属性 'invalid',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44589415/

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