首页 > 解决方案 > 角度反应形式和跨度标记中的显示错误

问题描述

我有这样的反应形式

https://stackblitz.com/edit/angular-form-array-duplicate-validation-ese9ap?file=src/app/app.component.ts

在表单中,只要有重复的用户,我希望 isNameDup() 为用户名数组中的每个元素触发。

我想在输入标签后向最终用户表明存在错误。

我不确定 *ngIf 子句应该是什么。

我的尝试是

<span *ngIf="creds.get('username').errors?.isNameDup">
              please enter some other name
</span>

在 stackbiltz 中,我需要以某种方式将第 17 行替换为第 19 行,以便 if 条件评估为 true,并且出现消息 please enter some other name text。

标签: angular

解决方案


尝试这个

function isNameDup() {
  const validator: ValidatorFn = (formArray: FormArray) => {  
    const control= formArray.controls
      .map(control => control.value);
      const names = control.map(value=> value.username)
       const hasDuplicate = names.some(
    (name, index) => names.indexOf(name, index + 1) != -1
  );  
     return  hasDuplicate ? { duplicate: true } : null;
  }
  return validator;
}

分叉示例:https ://stackblitz.com/edit/angular-form-array-duplicate-validation-f54kxv


推荐阅读