2

我想在表单上添加一个反应式表单控件并触发错误:

多个自定义值访问器匹配具有未指定名称属性的表单控件

一切都分开工作,反应式表单验证,掩码或matDatepicker,任何一对组合也可以工作,但三者一起提示错误。

这是我的代码:

在组件.ts

formGroup = new FormGroup({
    date: new FormControl()
  });

在 component.html 中

    <mat-form-field>
      <input type="text" matInput [matDatepicker]="date_picker" mask="d0/M0/0000" formControlName="date">
      <mat-datepicker-toggle matSuffix [for]="date_picker"></mat-datepicker-toggle>
      <mat-datepicker #date_picker></mat-datepicker>
    </mat-form-field>

我正在使用:

"@angular/cli": "8.3.19"
"ngx-mask": "8.1.7"
"@angular/material": "8.2.3"
4

2 回答 2

1

我正在努力解决同样的问题。根据这个线程,没有解决方案只有一种解决方法: 错误:多个自定义值访问器与未指定名称属性的表单控件匹配

我使用了提到的解决方法,将 vanilla-text-mask 作为临时(我希望)解决方案,但上述线程上没有任何活动,所以......这是解决方法的链接: 在一个输入中使用多个 CustomValueAcessor场地

希望能帮助到你!

于 2020-06-08T10:34:47.710 回答
1

我的解决方案:

1 - 在日期输入下方创建一个辅助屏蔽输入,使用 NgModel 将其值绑定到日期输入。(不要在屏蔽输入上使用 matInput 指令!)

 <input #dateInput matInput formControlName="control"  [matDatepicker]="picker" etc.../>
 <input #maskedInput [(ngModel)]="dateInput.value" mask="00/00/0000" [dropSpecialCharacters]="false" etc.../>

2 - 使用 css 隐藏日期输入:

input:first-child {
  height: 0;
  width: 0;
  overflow: hidden;
}

3 - 将焦点事件从日期输入中继到屏蔽输入

<input #dateInput (focus)="maskedInput.focus()" etc...>
<input #maskedInput etc...>

4 - 将输入事件从屏蔽输入中继到日期输入

<input #dateInput etc.../>
<input #maskedInput (input)="dispatch(dateInput)" etc.../>

5 - 在组件 ts 中创建一个 'dispatch' 函数

dispatch(input: HTMLInputElement){
    input.dispatchEvent(new Event('input'));
}

工作演示: https ://stackblitz.com/edit/angular-ivy-gyy1i4?file=src%2Fapp%2Fapp.component.ts

于 2020-12-04T21:33:49.823 回答