Search code examples
angularcomponents

Angular - how to pass the result of different pipes into a child component


I'm working on a project with Angular 8.

I have 2 variables in my parent component.

I want to pass them through a pipe and have the result go into a child component.

parent component:

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');
    }

}

parent component template:

            <ns-title-toggle-with-buttons
                [title]="(showStartWeek | momentDateFormat) - (showEndWeek | momentDateFormat)"
                (increment)="onIncrement()"
                (decrement)="onDecrement()"
            ></ns-title-toggle-with-buttons>

It does not give the desired result. It gives 'NaN'.

How can I pass in the final result to the child?

My pipe:

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);
    }
}

Solution

  • The problem is that inside the [title] you are subtracting two strings from each other. Try changing that to

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