Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular Reactive Form Tips #420

Open
JounQin opened this issue Feb 18, 2022 · 0 comments
Open

Angular Reactive Form Tips #420

JounQin opened this issue Feb 18, 2022 · 0 comments

Comments

@JounQin
Copy link
Owner

JounQin commented Feb 18, 2022

  1. 校验 FormControl 如果需要与其他 FormControl 联动检查时,应该在向上一级的 FormGroup 中设置相关 Validator 并在其中调用 control.setErrors() 来设置校验结果,这样可以保证多个 FormControl 变动时只需要进行一次校验。

示例代码:

export const domainValidator = (group: FormGroup) => {
  const prefixCtrl = group.get('prefix')
  const prefix: string = prefixCtrl.value
  const suffix: string = group.get('suffix').value
  const isPrefixValid =
    prefix.length + (suffix.length - +suffix.startsWith('*')) <= 20
  prefixCtrl.setErrors(isPrefixValid ? null : { maxlength: true })
}

export class TestComponent {
  form = this.fb.group(
    { prefix: '', suffix: '' },
    { validators: domainValidator },
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant