【问题标题】:Angular reactive form validator is showing error message initially?Angular 反应式表单验证器最初显示错误消息?
【发布时间】:2019-03-13 19:20:54
【问题描述】:

我有一个反应式表单验证器示例。在我们输入值之前,它最初会显示验证错误消息。

预期的行为是,输入值后必须显示错误消息

sample link

【问题讨论】:

标签: angular typescript validation angular-reactive-forms


【解决方案1】:

你必须检查你的错误信息是这样的

 <div *ngIf="check.errors.required && check.touched" class="e-error">
                This field is required.
 </div>

当您加载表单时,您正在检查 required ,那么您的字段显然是空的,所以它会抛出错误。

您将在此处获得更多信息和示例:Built In ValidatorsReactive Form Validattions

【讨论】:

    【解决方案2】:

    创建一个表单服务并使用 Mark FormGroup Touched 以便它默认不显示错误消息

    import { FormService } from './services/form';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.scss' ]
    })
    
    export class AppComponent  {
     public testForm: FormGroup;
    
    ngOnInIt(){
     this.testForm.valueChanges.subscribe((data) => {
        this.FormService.markFormGroupTouched(this.testForm);
    })
    }
    }
    

    【讨论】:

    • 嗨,Balaji,感谢您的支持....您是否用我的样本检查过这个...但它不起作用
    • 能否请您将您的想法应用到该示例中。?
    • @kumaresan_sd 肯定会将此应用到您的解决方案中,请稍候
    猜你喜欢
    • 1970-01-01
    • 2016-03-05
    • 2017-09-09
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2018-07-22
    • 2020-09-07
    • 2020-11-06
    相关资源
    最近更新 更多