【问题标题】:Angular - how to pass the result of different pipes into a child componentAngular - 如何将不同管道的结果传递给子组件
【发布时间】: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


【解决方案1】:

问题在于,在 [title] 中,您将两个字符串相减。尝试将其更改为

[title]="(showStartWeek | momentDateFormat) + ' - '+ (showEndWeek | momentDateFormat)"

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 2015-04-20
    • 2022-10-25
    • 1970-01-01
    • 2021-11-22
    • 2020-12-19
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多