【发布时间】:2020-06-03 08:26:03
【问题描述】:
我已经在我的 Angular 应用程序中使用 ControlValueAccessor 创建了一个简单的自定义 input 组件。所以,当我想创建一个表单input元素时,我不必调用<input />,只需调用<my-input>即可。
我有一个问题,当我使用<input />时,我可以使用myDirective。例如:
<input type="text" class="form-control" formControlName="name" myDirective />
但是,当我使用my-input 时,我不能使用myDirective。例如:
<my-input formControlName="name" myDirective></my-input>
myDirective 在我的输入中不起作用
这是my-input组件使用ControlValueAccessor代码:
import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Component({
selector: 'my-input',
templateUrl: './my-input.component.html',
styleUrls: ['./my-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MyInputComponent ),
multi: true
}
]
})
export class MyInputComponent implements ControlValueAccessor {
onChange: () => void;
onTouched: () => void;
value: string;
writeValue(value: string): void {
this.value = value ? value : '';
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
更新: myDirective 代码:
import { Directive, HostListener } from '@angular/core';
import { FormControlName } from '@angular/forms';
@Directive({
selector: '[myDirective]'
})
export class MyDirective{
constructor(private formControlName: FormControlName) { }
@HostListener('input', ['$event'])
onInputChange() {
this.formControlName.control.setValue(this.formControlName.value.replace(/[^0-9]/g, ''));
}
}
myDirective 有没有办法在my-input 组件中使用?
提前致谢。
【问题讨论】:
-
发布
myDirective实施 -
我之前被添加到我的问题中:
<my-input formControlName="name" myDirective></my-input>
标签: angular angular-directive controlvalueaccessor