javascript - 角度组件变量返回未定义
问题描述
我正在使用 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。
谢谢你的帮助。
解决方案
更改这些行
public changed: ( value: string ) => void;
public touched: () => void;
至
public changed: any = ( value: string ) => void; // personally I prefer {} rather than void
public touched: any = () => void;
推荐阅读
- python - 如何在python中批量重命名具有相同名称和不同扩展名的多个文件
- javascript - 为什么我的动态创建的 SVG 在查看时和使用 svg2pdf 打印时不同?
- docker - 用于具有多个 DockerProject 的解决方案的 Azure DevOps 构建管道
- javascript - 关闭 Safari 选项卡时获取 Javascript 句柄回调
- python - 无法理解对象在 Python 中是如何工作的
- python - 使用 OpenCV 测量弯曲线的真实角度
- tfs - 在 TFS 中添加 WinForms 并对其进行管理
- java - Spring Framework 和 Apache CXF 中的自定义 JSON 序列化
- codenameone - 多按钮显示问题 - 数据不显示
- amazon-web-services - 如何在无需重新上传的情况下本地测试 AWS Codepipeline (Codebuild+Codeploy)