首页 > 解决方案 > 角度组件变量返回未定义

问题描述

我正在使用 Angular 10,并且在使用 ControlValueAccessor 创建输入组件时遇到了问题。

我正在创建公共变量和公共箭头函数,当我调用箭头函数时返回未定义。

这是我的 .ts 代码:

import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, FormControl, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms';


@Component({
    selector: 'app-input',
    templateUrl: './input.component.html',
    styleUrls: ['./input.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(
                () => InputComponent
            ),
            multi: true
        }
    ]
})
export class InputComponent implements ControlValueAccessor {
    @Input() public parentForm: FormGroup;
    @Input() public fieldName: string;
    @Input() public label: string;

    public value: string;
    public changed: ( value: string ) => void;
    public touched: () => void;
    public isDisabled: boolean;

    get formField (): FormControl {
        return this.parentForm?.get( this.fieldName ) as FormControl;
    }

    constructor () { }

    public writeValue ( value: string ): void {
        this.value = value;
    }

    public onChange ( event: Event ): void {
        const value: string = (<HTMLInputElement>event.target).value;
        this.changed( value );
    }

    public registerOnChange ( fn: any ): void {
        this.changed = fn;
    }

    public registerOnTouched ( fn: any ): void {
        this.touched = fn;
    }

    public setDisabledState ( isDisabled: boolean ): void {
        this.isDisabled = isDisabled;
    }
}

还有我的 .html 文件:

<div class="form-group">
  <label class="form-label" [for]="fieldName">
    {{ label }}
  </label>

  <input
    type="text"
    class="form-control"
    [ngClass]="{ 'has-error': formField?.invalid && formField?.dirty }"
    [id]="fieldName"
    [name]="fieldName"
    [value]="value"
    [disabled]="isDisabled"
    (input)="onChange( $event )"
    (blur)="touched()"
  />

  <app-field-errors [formField]="formField">
  </app-field-errors>
</div>

当我与输入交互(更改/输入或模糊)时,我收到此错误:

ERROR TypeError: this.changed is not a function

ERROR TypeError: ctx.touched is not a function

我相信 this.changed 错误是因为我正在调用 onChange 函数,而 ctx.touched 是因为我正在调用 HTML 文件。

我可以正常访问 Input() 变量,例如 parentForm、fieldName 和 label。

谢谢你的帮助。

标签: javascriptangularvariables

解决方案


更改这些行

    public changed: ( value: string ) => void;
    public touched: () => void;

    public changed: any = ( value: string ) => void; // personally I prefer {} rather than void
    public touched: any = () => void;

推荐阅读