Angular2: Find out if FormControl has required validator?

前端 未结 7 774
无人共我
无人共我 2020-12-06 08:50

does someone know a way to find out for an Angular2 FormControl if the required validor is registered for the control.

this.form = builder.group({name: [\'\'         


        
7条回答
  •  死守一世寂寞
    2020-12-06 09:43

    With the assumption that the only error registered initially is the required error

    // in your component you'll have access to `this.myFormGroup`
    const formGroup = {
      controls: {
        email: {
          errors: {
            required: true
          }
        },
        username: {
          errors: null
        }    
      }
    }
    
    // required by default
    let required = {
      email: '*',
      username: '*',
    };
    
    // in `ngOnInit`
    required = Object.entries(formGroup.controls)
      .map(([key, control]) => [key, control.errors])
      .filter(([, errors]) => !errors)
      .map(([key]) => [key, ''])
      .reduce((_required, [key, isRequired]) => Object.assign(_required, { [key]: isRequired }), required)
    
    // in your template you may write ``
    console.log(required)

提交回复
热议问题