"Discover a new approach to incorporating the ChangeDetectorRef service into your pipe functions

I am facing an issue while trying to inject the ChangeDetectorRef service into my custom pipe in Angular. The error I am encountering is: No provider for ChangeDetectorRef!

Although I have looked at various examples related to similar functionalities (such as Translate pipe or async pipe), I am unable to make it work for my custom pipe...

Below is the code for my custom pipe:

import {Injectable, Pipe, PipeTransform, ChangeDetectorRef, OnDestroy} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';

@Injectable()
@Pipe({
    name: 'CollectionTranslation',
    pure: false
})

export class CollectionPipe implements PipeTransform, OnDestroy {
    value: string;
    lastKey: string;

    onLangChange: Subject<LangChangeEvent>;

    constructor(private translate: TranslateService, private _ref:   ChangeDetectorRef) {

    }

    updateValue(key: string, lang: string) {
        this.value = this.collectionTranslation(key, lang);
        this.lastKey = key;
        this._ref.markForCheck();
    }

    transform(collectionParam: string) {
        // lang parameter is just here to execute the pipe each time the current lang is changed.
        // it's not used in the pipe

        if (this.lastKey === collectionParam) {
            return this.value;
        }

        this.updateValue(collectionParam, localStorage.getItem('kia.language'));

        if (!this.onLangChange) {
            this.onLangChange = this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
                if (this.lastKey) {
                    this.lastKey = null; // we want to make sure it doesn't return the same value until it's been updated
                    this.updateValue(collectionParam, event.lang);
                }
            });
        }

        return this.value;
    }

    private collectionTranslation(collectionParam: string, lang: string): string {
        let collection = '';
        if (collectionParam === null || collectionParam === undefined) {
            return '';
        }

        const coll = collectionParam.toUpperCase();
        if (lang === 'fr') {
            collection = coll.startsWith('E') || coll.startsWith('S') ? 'ETE ' : 'HIVER ';
        } else {
            // Lang EN
            collection = coll.startsWith('E') || coll.startsWith('S') ? 'SUMMER ' : 'WINTER ';
        }

        collection = collection + coll.substring(coll.length - 2);

        return collection;
    }

    _dispose(): void {
        if (typeof this.onLangChange !== 'undefined') {
            this.onLangChange.unsubscribe();
            this.onLangChange = undefined;
        }
    }

    ngOnDestroy(): void {
        this._dispose();
    }
}

I believe that adding the ChangeDetectorRef to the module is unnecessary as it is a core functionality.

Thank you for your assistance!

Answer №1

In my opinion, it would be better to utilize the ApplicationRef instead of the ChangeDetectorRef since the latter only detects changes in a specific component. I recommend trying to achieve the same result with the former.

Could you please share your Component.ts file where you demonstrate the usage of this pipe? Also, did you remember to include both the pipe and the Detector in the providers array?

I hope this suggestion proves helpful.

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

Obtain text output from an Observable

After retrieving a String from the backend: String value = "{I am here}"; In my service method: getValue(): Observable<String> { return this.http.get<String>(this.myURL); } In my component, I am subscribing to this method: String myM ...

Vitest's behavior shows variance when compared to compiled JavaScript

Challenge Currently, I am developing a package that relies on decorators to initialize class object properties. The specific decorator is expected to set the name property of the class. // index.ts const Property = (_target: any, key: any) => { } cl ...

Please indicate the generator title (for example, nx generate @nrwl/workspace:library) specifically for Angular

Currently, I am expanding my knowledge in web development. While working with Angular, I encountered an issue when trying to create a new component. The error message reads "Specify the generator name (e.g., nx generate @nrwl/workspace:library)" after exec ...

Implement a conditional block in my form validation process

Greetings, I have hit a roadblock with this issue for the past few days Here's the problem: I have an input field where I need to display a message based on certain conditions. One condition specifies that if it is a multiline text, use a textarea; o ...

Securely transfer data between objects using a for loop

Description I have two similar types that are not identical: type A = { a?: number b?: string c?: boolean } type B = { a?: number b?: string c?: string } I am looking to create an adapter function f() that can convert type A to type B, with ...

Accessing properties in Angular/TypeScript: extracting values from a partially extended interface

I am fairly new to Angular/TS and I may not have worded this correctly, but I will do my best to explain. I have defined 2 interfaces where one extends the other as shown below: export interface CustomerModel { firstName: string; lastName: string; ...

What is the best way to invoke a function in a functional React component from a different functional React component?

I need to access the showDrawer method of one functional component in another, which acts as a wrapper. What are some best practices for achieving this? Any suggestions or insights would be appreciated! const TopSide = () => { const [visible, se ...

Troubleshooting Problem in Angular 6: Difficulty in presenting data using *ngFor directive (data remains invisible)

I came across a dataset that resembles the following: https://i.sstatic.net/S0YyO.png Within my app.component.html, I have written this code snippet: <ul> <li *ngFor="let data of myData">{{data.id}}</li> </ul> However, when I ...

JavaScript modules in Node.js do not support non-relative imports properly with Typescript

My goal is to develop a straightforward TypeScript script that utilizes ES modules, runs with node, and includes sourcemaps for debugging purposes. Here's the script that runs with node test.ts: import foo from './foo' //import bar from &a ...

The Angular 13 application encounters a "moment is not a function" error after importing an Angular 13 package

Upgrading a private library named privLib to Angular 13 has been my recent task in order to facilitate the migration of all other projects. However, an issue arises when this library is imported into another project where one of the services utilizes momen ...

Angular Universal build stuck on rendering page while waiting for API response

I'm currently developing a compact web application using the angular universal starter in combination with pokeapi. To enhance performance and reduce API requests, I intend to implement pre-rendered pages since the data displayed remains mostly static ...

Release a new font on npm for integration into your project

In my current web-application project using angular2, I've designed a unique set of music glyphs such as notes, dotted notes, and time signatures. I couldn't find an existing font that suited my needs, so I created this custom font hierarchy: f ...

Tips for developing a strongly-typed generic function that works seamlessly with redux slices and their corresponding actions

Currently, I am working with @reduxjs/toolkit and aiming to develop a function that can easily create a slice with default reducers. Although my current implementation is functional, it lacks strong typing. Is there a way to design a function in such a man ...

Tips on implementing npm's node-uuid package with TypeScript

Whenever I attempt to utilize node-uuid in TypeScript, I encounter the following issue: Cannot find module uuid This error occurs when I try to import the uuid npm package. Is there a way to successfully import the npm uuid package without encountering ...

How can I incorporate piping into an input field when working with Angular 2?

Just starting out with angularJS2 and looking to add a pipe to the input type text in a form. For example, if I have an input tag like this <input type="text" class="col-lg-7 small rounded form-control" formControlName="firstName" /> I'd like ...

When utilizing a [ngSwitch] with the toolbar (md-toolbar) in Angular2, the buttons fail to load correctly

I am currently designing a toolbar that includes a menu button using the following code: <md-toolbar class="header"> <div class="header-wrapper m-x-30 clearfix"> <div class="logo-container"> <div class="logo-image align-middle" ...

How do I condense nested keys in TypeScript?

If I have two types defined in TypeScript: interface Foo { bar: string; } interface Baz { foo: Foo; } Is it possible to flatten the Baz type in TypeScript (e.g. type FlatBaz = Flatten<Baz>), so that the signature appears similar to this? inte ...

Module error caused by Typescript path inconsistency

After creating a new model named "project" within the existing project, I encountered an error when attempting to import the class into another typescript file in VS2019. The specific error message thrown is as follows: "ts2307 cannot find module ' ...

Tips for managing table scroll in a flexbox design

Check out the demo here I am working with a table that has an indefinite number of rows and columns. When the table has a small number of rows and columns, it adjusts its width according to the available page space minus the width of the sidebar. Everythi ...

Converting the 'require' call to an import may be a more efficient method when importing package.json in a typescript file

In my current project, I am creating a class where I am directly accessing the package version number like this: const pkg = require('../package.json') export class MyClass() { constructor() { // Set the base version from package.jso ...