網站搜尋

angular - 如何以程式方式將錯誤附加到 FormGroup 控制項?


在我的動態 FormGroup 中,我想要程式化地向表單控制項添加一個錯誤,但我看到的唯一添加錯誤的方法是這樣

this.userForm.controls.username.setErrors({
  'exists': 'Username already exists'
});

這會完全取代任何現有的錯誤。有沒有辦法將單一錯誤附加到動態 FormGroup 控制項?

答案#1

control.setErrors({ ...(control.errors || {}), 'newError': 'text of the error' })

你只需要取得先前的錯誤,並將它們擴展到你的新錯誤物件中。

control.errors || {}

是一種對不可擴散值(例如 undefined 或 null)的保護

答案#2

使用展開運算符

const errors = this.userForm.controls.username.errors || {};
this.userForm.controls.username.setErrors({
  'exists': 'Username already exists', ...errors
})