如何在带有ControlValueAccessor角的自定义输入中使用指令

问题描述 投票:1回答:2

我已经在我的角度应用程序使用input中创建了一个简单的自定义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在我的输入中不起作用

这是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

提前感谢。

angular angular-directive controlvalueaccessor
2个回答
1
投票

您的指令有问题。注入NgControl并控制此ngControl


1
投票

您不能直接使用,但可以使用指令查询来做一些修改

© www.soinside.com 2019 - 2024. All rights reserved.