首页 > 解决方案 > 在角度 8 中为 FormControl 创建扩展方法

问题描述

我想为 formGroup 创建一个扩展,以将波斯日期转换为戈尔吉日期。

这是我的扩展代码:

   import { FormControl } from '@angular/forms'

export { }

declare global {
    interface FormControl {
        ToMiladidate(date: Date): string;
    }
}

FormControl.prototype.ToMiladidate = function (date: Date): string {
    if (!date)
        return this;
    return new Date(date).toISOString();
}

但在这一行中,它向我显示错误:

FormControl.prototype.ToMiladidate

告诉我这个错误:

“FormControl”类型上不存在属性“ToMiladidate”

有什么问题 ?我怎么解决这个问题 ???

标签: javascriptangulartypescript

解决方案


如果这个问题仍然相关,这里是答案:

declare module '@angular/forms' {


interface AbstractControl {
    ToMiladidate(date: Date): string;
  }
}

AbstractControl.prototype.ToMiladidate = function (date: Date): string {
  if (!date)
    return this;
  return new Date(date).toISOString();
}

解决方案是使用 AbstractFormControl 而不是 FormControl 并声明不是全局模块而是@angular/forms。如果您需要在导入顶部将原型导入app.module.ts时在单独的文件中声明原型:

import './form.prototype';

推荐阅读