Exporting a function for a custom pipe in Angular 2

I have a navigation component where I need to call a method that applies a custom pipe. However, when trying to reference it, the console displays an error stating "filterPortfolio is not defined".

The method is being bound to a click event in my DOM (the html is applied by the navigation component).

Here is a snippet of my HTML:

<div id="filter1" class="miniNavButton" *ngIf="portfolio" (click)="changeFilter('demo')">
    <a>
        <svg class="icon icon-eye">
            <use xlink:href="symbol-defs.svg#icon-eye"></use>
        </svg>
    </a>
</div>

In my portfolio.component.ts file:

import { Component } from 'angular2/core';
import {ViewEncapsulation} from 'angular2/core';
import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({ name: 'pagesFilter' })
class pagesFilter implements PipeTransform {
    transform(pages, [key]): string {
        return pages.filter(page => {
            return page.hasOwnProperty(key);
        });
    }
}

@Component({
    selector: 'portfolio',
    templateUrl: '/app/views/portfolio.html',
    styleUrls: ['../app/styles/PortfolioMobile.css', '../app/styles/PortfolioOther.css'],
    pipes: [pagesFilter],
    encapsulation: ViewEncapsulation.None
})

export class PortfolioComponent {
    // Pages data here...
    
    filterPortfolio(parameter:String) {
        return this.pages ? 'pagesFilter' : parameter
    };
}

In navigation.component.ts:

import { Component } from 'angular2/core';
import {ViewEncapsulation} from 'angular2/core';
import { Router, ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig } from 'angular2/router';

import { LandingComponent } from './landing.component';
import { PortfolioComponent } from './portfolio.component';
import { SkillsComponent } from './skills.component';
import { ContactComponent } from './contact.component';

@Component({
    selector: 'my-navigation',
    templateUrl: '/app/views/navigation.html',
    styleUrls: ['../app/styles/navigationMobile.css', '../app/styles/navigationOther.css'],
    encapsulation: ViewEncapsulation.None,
    directives: [ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS]
})

export class NavigationComponent {
   // Functions for changing mini nav state and calling filter
    
    changeFilter(a) {
        PortfolioComponent.apply(filterPortfolio(a));
    }
}

This is how the HTML iterates through the pages object:

<div class="portfolioContainer">
    <div *ngFor="#p of pages" class="portfolioPageContainer">
        <img [attr.src]="p.img" class="portfolioThumbnail">
        <h2>{{ p.name }}</h2>
        <a [attr.href]="p.repo">
            <div>
                <p>{{ p.description }}</p>
            </div>
            <p class="portfolioRepoLink">See the Code!</p>
        </a>
    </div>
</div>

If anyone can suggest what might be causing the issue, it would be highly appreciated. Thank you.

Answer №1

The filterPortfolio method is a key component of the PortfolioComponent class, and can be called in the following ways. It seems like there may be an issue with how you are using the apply method:

PortfolioComponent.prototype.filterPortfolio.apply(this, [a]);

Alternatively, you can use the call method:

PortfolioComponent.prototype.filterPortfolio.call(this, a);

However, it appears that the usage of the pagesFilter pipe is not properly implemented in your code.

In a similar case, Günter provided a helpful solution in the past. Further details can be found in this question:

  • Angular2 - assign pipe from a variable

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving JSON files within karma tests

I am currently working on developing a test for my TypeScript class that involves retrieving data from a JSON file. readData<T>(filePath: string): Promise<T> { return Qajax.getJSON(filePath); } For testing purposes, I am utilizing the Jas ...

Is it possible to verify or authenticate the properties received directly from the associated type or interface?

Looking for a more efficient way to handle validation in my component that takes an array of tabs and children as props. I would like to check if the children provided are the same length as the tabs array directly from the type declaration or any cleaner ...

What steps should I take to maximize the efficiency of my angular function?

Hey there, I could really use some assistance with optimizing this code snippet. Does anyone have any ideas on how to improve it? Here's the code: optimizeCode(value, fieldName: string) { if (fieldName === 'fullName') { this.billingFields. ...

Make sure that the Chai assertion does not result in any errors

One of my functions involves retrieving file content. export function getFileContent(path: string): any { const content = readFileSync(path); return JSON.parse(content.toString()); } If I need to verify that calling getFileContent(meteFile) result ...

Top Method for Dynamically Adding Angular Component on Click Action

As I develop my website, I am faced with the challenge of incorporating multiple components. One specific feature involves allowing users to dynamically add a component of their choice to the "Home" page when they click a button. I have explored three diff ...

DiscoverField Component with Button Functionality and Checkbox Dilemma

I'm working with Vue 3, Vuetify, and TypeScript for my searchField component. Inside, I have two buttons: FreeItemMaster and PatternMaster. Clicking on these buttons should change their background color and display respective content below them. Howev ...

Filter a two-dimensional array based on the presence of a string value found in the second array

My logic for this assignment is not very good, as I need to filter a 2D array based on the values of another array. Let me provide an example of the 2-Dimensional Array: const roles = [ ['roles', 'admin', 'write'], ['ro ...

Guide to developing a private shared Node.js module using TypeScript

I have a unique idea for a nodejs server service, consisting of: a REST API, and various asynchronous workers. My vision is to separate these components into different subnets and git repositories while still enabling them to access the same database en ...

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

Extract values from an object using Typescript

Here is my JavaScript code: const { a, b, c } = { a : "hello", b : "stackoverflow", c : "it's greate" }; I am interested in converting this to TypeScript. Is there any solution for this? ...

Angular: Design dependent on attributes

Can I customize the styling of a div in accordance with a boolean property called "isActive" on my controller using Angular? <div class="col-md-3" (click)="isActive = !isActive"> <div class="center"> <i class="fa fa-calendar"& ...

Using Ionic2, include NavController into Injectable Service

Having an issue with an Injectable Service in Angular2 with Ionic2 framework. Here is how my service is structured: import {Injectable} from '@angular/core'; import {NavController} from 'ionic-angular'; @Injectable() export class Vie ...

Using Ionic 2 to Replace Local File with HTTP Plugin

Currently, I am in the process of developing an Ionic 2 hybrid app that retrieves a settings.json file using http.get('build/settings.json') during startup. One of my goals is to allow the client to make changes to these settings, and ultimately ...

Is there a specific instance where it would be more appropriate to utilize the styled API for styling as opposed to the sx prop in Material-

I am currently in the process of migrating an existing codebase to Material UI and am working towards establishing a styling standard for our components moving forward. In a previous project, all components were styled using the sx prop without encounteri ...

What is the best way to test chained function calls using sinon?

Here is the code I am currently testing: obj.getTimeSent().getTime(); In this snippet, obj.getTimeSent() returns a Date object, followed by calling the getTime() method on that Date. My attempt to stub this functionality looked like this: const timeStu ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection. Error Occurred <inpu ...

Guide to displaying loading progress during server response delay in React with TypeScript

I need to find a way to update the loading state to false once the server responds. The challenge is that the response occurs in one component, while the progress bar is located in another. To illustrate the scenario: const Form: React.FC = () => { ...

Show a checkmark or X depending on the condition in Javascript

I have an array of data that I want to compare to the input in a text field. If the input matches an element in the array, I want to display a checkmark, and if it doesn't match, I want to display a crossmark. However, I'm having an issue where ...

Mastering the mapping function in ReactJs for a Map<string, boolean> data structure

Just a quick question, I seem to be stuck on this. Here is my Map: public checkboxOptions: Map<string, boolean>; In the render() function, I want to loop through it like this: renderCheckboxMenu(): any { let menu = <div className={`${style[ ...