在Angular 2模板中使用原型

时间:2017-07-14 00:13:35

标签: javascript html angular typescript

如何在Angular 2模板中使用自定义原型?附件是我写的原型。这在我的单元测试以及任何Angular 2组件打字稿文件中都非常有效。但是,如果我尝试在Angular 2 html模板文件中使用它,则会抛出异常,指出toUtcDate()不是指定日期对象的函数。

我怀疑我必须以某种方式将这个原型引导到我的应用程序模块中,但我目前在如何继续进行中处于亏损状态。

interface Date {
    toUtcDate(): string;
}

Date.prototype.toUtcDate = function(): string {
    var utcMonth = this.getUTCMonth() + 1;
    var utcDate = this.getUTCDate();

    var year = this.getUTCFullYear();
    var month = utcMonth < 10 ? '0' + utcMonth : utcMonth;
    var day = utcDate < 10 ? '0' + utcDate : utcDate;
    var hours = this.getUTCHours() < 10 ? '0' + this.getUTCHours() : this.getUTCHours();
    var minutes = this.getUTCMinutes() < 10 ? '0' + this.getUTCMinutes() : this.getUTCMinutes();
    var seconds = this.getUTCSeconds() < 10 ? '0' + this.getUTCSeconds() : this.getUTCSeconds();
    var milliseconds = this.getUTCMilliseconds() < 10 ? '0' + this.getUTCMilliseconds() : this.getUTCMilliseconds();
    return (year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds + '.' + milliseconds + 'Z');
}

1 个答案:

答案 0 :(得分:0)

我不确定要实现此目标的另一种方法,但这是Angular 9中的一个有效示例。

我将String对象扩展如下(file = string.extensions.ts):

export { };

declare global {
    interface StringConstructor {
        isNullOrEmpty(value: string): boolean;
    }
}

if (!String.isNullOrEmpty) {
    String.isNullOrEmpty = function (value: string): boolean {
        if (value === undefined || value === null) {
            return true;
        }

        if(value != null && value.trim() === '') {
            
            return true;
        }

        return false;
    }
}

在您的组件中,您需要导入string.extensions文件(该路径很重要,以便正确使用):

import './yourPath/string.extensions.ts';

这使它在组件的TS文件中可用。例如

import './yourPath/string.extensions.ts';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

  constructor() {
    const testString = 'test';
    console.log(String.isNullOrEmpty(testString)); //false

    const anotherTestString = null;
    console.log(String.isNulleOrEmpty(anotherTestString)); //true
  }

  ngOnInit() {}
}

最后令人讨厌的一点-使它在模板中运行。您需要做的就是声明您要扩展的类型的公共变量。例如

String = String;

因此,先前的示例组件TS文件现在将如下所示:

import './yourPath/string.extensions.ts';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {

  constructor() {}

  String = String;
  stringToTest = null;

  ngOnInit() {}
}

并在您的HTML模板中使用它:

<div *ngIf="!String.isNullOrEmpty(stringToTest)">
  string was not empty or null
</div>