[英]Can I return a string value via angular custom validation method
Here is my working validation method (but notice where I try to sneak in res):这是我的工作验证方法(但请注意我尝试潜入 res 的位置):
checkIfEmailExists(email: string): Observable<object | null> {
return this.store.pipe(
select(selectAssigneeNameByEmail(email)),
debounceTime(500),
take(1),
map(name => {
return res ? { alreadyExists: true, name } : null;
})
);
and here is where I call it in component (and would like to also consume the name from above but how? Pipe?:这是我在组件中调用它的地方(并且还想从上面使用名称但是如何使用?Pipe?:
alreadyExists(control: AbstractControl): object {
return this.emailAlreadyExistsValidator.checkIfEmailExists(control.value)
}
html: html:
<mat-error *ngIf="form.get('email').hasError('alreadyExists')">email already associated with {{name}}</mat-error>
So, I just want to be able to use res from above to say, sorry that email is already associated with {{name}}所以,我只想能够使用上面的 res 说,对不起 email 已经与 {{name}} 关联
since your error object returned from the validation already returns the name (via {alreadyExists: true, name}
object), you can simply get it from the form:由于您从验证返回的错误 object 已经返回了名称(通过
{alreadyExists: true, name}
对象),您可以简单地从表单中获取它:
<mat-error *ngIf="form.hasError('alreadyExists', 'email')">
email already associated with {{ form.getError('name', 'email') }}
</mat-error>
A good idea IMO would be to return the associated error message straight from the validator: IMO 的一个好主意是直接从验证器返回相关的错误消息:
return res ? { alreadyExists: `E-mail already associated with ${name}` } : null;
And then on the HTML:然后在 HTML 上:
<mat-error *ngIf="form.getError('alreadyExists', 'email'); let errorMsg">
{{ errorMsg }}
</mat-error>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.