Get validators present in FormGroup/FormControl

前端 未结 5 1788
感动是毒
感动是毒 2020-12-10 11:03

I\'m using Material 2 in my app, but in this question I want to solve a problem specifically with Input.

As you can see in API Reference there\'s a

5条回答
  •  旧时难觅i
    2020-12-10 11:20

    Based on mtinner's commend https://github.com/angular/angular/issues/13461#issuecomment-340368046 we built our own directive to mark mandatory fields accordingly.

    @Directive({
      selector: '[mandatoryField]'
    })
    export class MandatoryFieldDirective implements OnInit {
    
      hasRequiredField(abstractControl: AbstractControl) {
        if (abstractControl.validator) {
          const validator = abstractControl.validator({} as AbstractControl);
          if (validator && validator.required) {
            return true;
          }
        }
        return false;
      }
    
      ngOnInit() {
        const required = this.hasRequiredField(this.ngControl.control);
        if (required) {
          this.renderer.setAttribute(this.elementRef.nativeElement, 'required', '');
    
          if (this.parentFormField && this.parentFormField._elementRef) { // required for Angular Material form-fields
            this.renderer.setAttribute(this.parentFormField._elementRef.nativeElement, 'required', '');
          }
        }
      }
    
      constructor(
        private ngControl: NgControl, @Optional() private parentFormField: MatFormField,
        public renderer: Renderer2, public elementRef: ElementRef
      ) { }
    
    }
    

    The directive sets a 'required' attribute. This attribute can be addressed via CSS. The directive works on normal HTML input tags as well as on Angular Material form fields. To work with Angular Material we had to add a little workaround as the 'required' attribute has to be set on the enclosing form field tag; not only on the actual input field. Therefore the parent component is pass-through to the directive constructor.

    
      
      
    
    

提交回复
热议问题