如何在Angular 2模板中使用自定义原型?附件是我写的原型。这在我的单元测试和任何Angular 2组件typescript文件中都能很好地工作。但是,如果我试图在Angular 2html模板文件中使用它,就会抛出一个异常,说明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');
}发布于 2020-10-28 15:47:40
我不确定有没有其他方法可以做到这一点,但这里有一个在Angular 9中工作的例子。
我扩展了字符串对象,如下所示(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>https://stackoverflow.com/questions/45092729
复制相似问题