【发布时间】:2020-11-30 12:32:15
【问题描述】:
我正在使用 Angular 8 开发一个项目。
我的父组件中有 2 个变量。
我想通过管道将它们传递给子组件。
父组件:
import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
@Component({
selector: 'ns-clockcard',
templateUrl: './clockcard.component.html'
})
export class ParentComponent implements OnInit {
public showStartWeek: moment.Moment;
public showEndWeek: moment.Moment;
constructor() {}
public ngOnInit(): void {
this.showStartWeek = moment().startOf('week');
this.showEndWeek = moment().endOf('week');
}
}
父组件模板:
<ns-title-toggle-with-buttons
[title]="(showStartWeek | momentDateFormat) - (showEndWeek | momentDateFormat)"
(increment)="onIncrement()"
(decrement)="onDecrement()"
></ns-title-toggle-with-buttons>
它没有给出想要的结果。它给出“NaN”。
如何将最终结果传递给孩子?
我的烟斗:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'momentDateFormat'
})
export class MomentDateFormatPipe implements PipeTransform {
transform(input: moment.Moment, desiredFormat?: string): string {
if (input == null) {
return '';
}
if (desiredFormat == null) {
return input.format();
}
return input.format(desiredFormat);
}
}
【问题讨论】:
-
momentDateFormat 管道似乎没有返回数字,这就是您收到此错误的原因
-
@Chellappanவ 感谢您的提示。我的单元测试通过管道顺利通过。
-
我认为 input.format(desiredFormat) 正在返回字符串值。您可以在管道内进行控制台并检查管道返回数值吗?
标签: angular components