是否可以在组件模板中使用第三方库,而不仅仅是在组件TS文件中?
我使用"date-fns"库,我想在模板中使用它来格式化日期。类似于此,其中"format"是"date-fns"库中的一个函数。
<span class="cell-time-horizon-value">
{{format(session?.timeHorizon.start, "yyyy-MM-dd")}}
</span>
最好的方法是使用Pipe
:
import { format } from 'date-fns';
@Pipe({
name: 'formatDate'
})
export class FormatDatePipe implements PipeTransform {
transform(value: string | number | Date, dateFormat: string): string {
return format(value, dateFormat);
}
}
<span class="cell-time-horizon-value">
{{session?.timeHorizon.start | format:"yyyy-MM-dd")}}
</span>
回答标题中问题的另一种方法是在组件中声明它。所以,如果你有:
<span class="cell-time-horizon-value">
{{format(session?.timeHorizon.start, "yyyy-MM-dd")}}
</span>
您可以通过更改组件类来实现这一点:
import { format } from 'date-fns';
export class TestComponent {
readonly format = format;
}