gpt4 book ai didi

angular - 如何使用 ControlValueAccessor Angular 在自定义输入中使用指令

转载 作者:行者123 更新时间:2023-12-03 22:00:10 25 4
gpt4 key购买 nike

我已经创建了一个简单的自定义 input我的 Angular 应用程序中的组件使用 ControlValueAccessor .所以,当我想创建一个表单 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 dosn't work in my-input



这是 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零件?

提前致谢。

最佳答案

你的指令有问题。注入(inject) NgControl并控制这个 ngControl

export class MyDirective{
constructor(private control: NgControl) { } //<--inject NgControl

@HostListener('input', ['$event'])
onInputChange() {
this.control.control.setValue(this.control.value.replace(/[^0-9]/g, ''));
}
}

您可以在 stackblitz 中查看

注意:不要忘记包含在模块声明中
@NgModule({
imports: [ BrowserModule, FormsModule,ReactiveFormsModule ],
declarations: [ AppComponent, MyInputComponent,MyDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

关于angular - 如何使用 ControlValueAccessor Angular 在自定义输入中使用指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60295756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com