How to display only single validation error at a time

后端 未结 6 1647
失恋的感觉
失恋的感觉 2021-02-08 02:35

I have this code to which displaying errors on my form


&         


        
6条回答
  •  攒了一身酷
    2021-02-08 03:24

    You could create a custom pipe to get the first element of the errors object of the validator:

    @Pipe({
      name: 'first'
    })
    export class FirstKeyPipe {
      transform(obj) {
        var keys = Object.keys(obj);
        if (keys && keys.length>0) {
          return keys[0];
        }
        return null;
      }
    }
    

    This way you would be able to display only one error:

    @Component({
      selector: 'my-app',
      template: `
        
    Required
    Custom
    `, pipes: [ FirstKeyPipe ] }) export class MyFormComponent { constructor(private fb:FormBuilder) { this.form = fb.group({ input1: ['', Validators.compose([Validators.required, customValidator])] }); } }

    See this plunkr: https://plnkr.co/edit/c0CqOGuzvFHHh5K4XNnA?p=preview.

    Note: agreed with Günter to create a usable component ;-) See this article for more details:

    • http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/

提交回复
热议问题