繁体   English   中英

为什么 Angular 中没有显示表单验证错误?

[英]Why form validation errors are not showing in Angular?

我已经在一个项目中工作了一周,最近我注意到我没有收到任何表单验证错误,我不知道为什么。

我尝试使用此代码,来自https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation

<form>
 <div>
   <label for="choose">Would you prefer a banana or a cherry?</label>
   <input type="text" id="choose" name="i_like" required minlength="6" maxlength="6">
 </div>
 <div>
   <label for="number">How many would you like?</label>
   <input type="number" id="number" name="amount" value="1" min="1" max="10">
 </div>
 <div>
   <button>Submit</button>
 </div>
</form>

我用代码替换了我的整个app.component.html并且没有显示验证消息,然后我替换index.html主体并且它可以工作,我不知道我的项目中可能存在什么问题。

我还尝试从项目中删除 angular.json scriptsstylesassets中的 boostrap 和任何依赖项,但仍未显示。

对于 2+ 版本以上的 angular,您需要创建反应式 forms。 请参考下面的代码

app.module.ts

您需要在 app.module.ts 中导入 ReactiveFormsModule

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  imports: [
    CommonModule,
    ReactiveFormsModule
  ]
})
export class AppModule {
}

现在您可以在 app.component.ts 中使用响应式表单

app.component.ts

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class AppComponent implements OnInit {
   myForm: FormGroup;

   constructor(
    private fb: FormBuilder
   ) {}

   ngOnInit() {
      this.myForm = this.fb.group({
         i_like: ['', Validators.required],
         amount: ['', Validators.required]
      });
   }

   onSubmit(): void{
   }
}

现在在您的app.component.html中,您需要创建表单

app.component.html

<form [formGroup]="myForm" (ngSumbit)="onSubmit()">
 <div>
   <label for="choose">Would you prefer a banana or a cherry?</label>
   <input type="text" id="choose" formControlName="i_like" required minl ength="6" maxlength="6">
   <p *ngIf="myForm.get('i_like').hasError('required')">Please select this field.</p>
 </div>
 <div>
   <label for="number">How many would you like?</label>
   <input type="number" id="number" formControlName="amount" value="1" min="1" max="10">
   <p *ngIf="myForm.get('amount').hasError('required')">Please select this field.</p>
 </div>
 <div>
   <button type="submit">Submit</button>
 </div>
</form>

您还可以在 Reactive Forms 中设置多种类型的验证器。 请参阅链接以获取更多参考。

验证在 angular 中的工作方式与普通 js 中的不同:

通常,响应式方式是首选,因为如果代码库变得更大,它可以更容易地重构为组件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM