ERROR: Angular 2 custom form input provider not found

I am currently working on incorporating

ControlValueAccessor

into a custom Angular 2 form input component.

However, I encountered an EXCEPTION:

EXCEPTION: No provider for MyDatePicker! (MyDatePickerValueAccessor -> MyDatePicker)

I have shared the code on Plunker:

Plunker Custom Control Event Binding Working

Plunker Custom Control Value Accessor Not Working

Additionally, here is my implementation of the ControlValueAccessor:

    import {MyDatePicker} from './MyDatePicker';
    import { Directive, Provider, forwardRef , } from 'angular2/core';
    import {ControlValueAccessor, NG_VALUE_ACCESSOR} from 'angular2/common';
    import {CONST_EXPR} from 'angular2/src/facade/lang';

    const CUSTOM_VALUE_ACCESSOR = CONST_EXPR(new Provider(
        NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => MyDatePickerValueAccessor), multi: false }));

    @Directive({
        selector: 'my-date-picker',
        host: { '(dateChanged)': 'onChange($event)' },
        providers: [CUSTOM_VALUE_ACCESSOR]
    })
    export class MyDatePickerValueAccessor implements ControlValueAccessor {
        onChange = (_) => { };
        onTouched = () => { };

        constructor(private host: MyDatePicker) { }

        writeValue(value: any): void {
            this.host.selDate = value;
        }

        registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
        registerOnTouched(fn: () => void): void { this.onTouched = fn; }
    }

For more information, check out some of the links from my research:

Answer №1

Attempt to compose

providers: [ANOTHER_CUSTOM_VALUE_ACCESSOR, MyDatePicker]

Answer №2

Thank you to ❤️@mnv❤️ and ❤️@eric-martinez❤️ for their assistance.

I am pleased to say that I have found a solution.


MyDatePicker.ts


  1. To address the issue, make the following update:

    setValue(value) {
        this.selectionDayTxt = value;
        if(this.selectionDayTxt !== '') {
          let fmt = this.options.dateFormat !== undefined ? 
                    this.options.dateFormat : this.dateFormat;
          let dpos = fmt.indexOf('dd');
          let mpos = fmt.indexOf('mm');
          let ypos = fmt.indexOf('yyyy');
          this.selectedDate = {day: parseInt(this.selectionDayTxt
                                .substring(dpos, dpos + 2)),
              month: parseInt(
                this.selectionDayTxt.substring(mpos, mpos + 2)),
              year: parseInt(
                this.selectionDayTxt.substring(ypos, ypos + 4))};
        }
        if(this.selectionDayTxt !== '') {
            this.selectionDayTxtForServer = 
                this.formatDateForServer(this.selectedDate);
        }
    }
    

2.Update the code as follows:

    ngOnChanges(changes: {[propName: string]: SimpleChange}) {
        this.setValue(changes['selDate'].currentValue);
    }   

MyDatePickerValueAccessor.ts


  1. Replace the existing code with:

    const CUSTOM_VALUE_ACCESSOR = CONST_EXPR(
    new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => 
                                MyDatePickerValueAccessor), multi: true }));
    
  2. Update the providers section to include:

    providers: [CUSTOM_VALUE_ACCESSOR , MyDatePicker,ElementRef]
    
  3. Modify the host configuration to:

    host: { '(dateChanged)': 'onChange($event.formattedForServer)' }
    
  4. Adjust the writeValue function as follows:

    writeValue(value: any): void {
        this.host.setValue(value);
    }
    

For a complete example, visit:

Explore the original mydatepicker project on Github:

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

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

"Is there a way to fix the issue where Express (node.js) res.send is only sending

Encountering unusual behavior with res.send() in the express framework. Below is the function causing the issue: user.register(function(err, result) { console.log(JSON.stringify(err || result)); res.send(JSON.stringify(err || result)); }); The f ...

Is there a way for me to position my arrow beside the header while still keeping the toggle function intact?

Can anyone assist me in positioning my arrow next to the header text, which I toggle on click? I attempted placing the arrow <div> into the H1 tag, but then the toggle function stops working. Any help would be greatly appreciated! Please includ ...

Finding the minimum value in a list and the maximum value in JavaScript

My current JavaScript list consists of dollar coin values: let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0] My challenge is finding an equation in JavaScript that will allow me to use the smallest number of coins to reach the desired max ...

Update the PHP webpage dynamically by utilizing AJAX and displaying the PHP variable

I am working on a PHP page that includes multiple queries, and I would like to be able to include this page in my index.php file and display the results with an automatic refresh similar to the Stack Overflow inbox feature. Is there a way to achieve this ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...

Utilizing React with Typescript to access specific props

I am a newcomer to React and TypeScript and I am facing a challenge while trying to enhance an existing component by creating a wrapper around it. The issue I am encountering is related to adding my custom values to the properties. My goal is to extend th ...

"Enhance your Angular application with seamless data manipulation by piping Observable

Currently, I am trying to pass an array value as a parameter to another function. The array is obtained from a subject: this.shopService.$getShops().pipe(map( shops => { console.log(shops[0]); } )).subscribe(); The subscription logic is implem ...

Run a JavaScript function in 5 seconds

I'm looking to execute this function after a 5-second delay: $(document).ready(function() { $("#signInButton").trigger('click'); }); Your assistance is greatly appreciated. ...

Cease the act of sending submissions through JavaScript ajax requests

I need to prevent a form submission based on the result of an ajax request... Here is the code I attempted to implement: The chreg() function is supposed to return a boolean value from the ajax request, but it's not working! Javascript: function ch ...

What is the process of extracting a value from an array of objects based on another parameter?

Given the array below which contains objects with nested arrays, my goal is to retrieve the value 'AUS Eastern Standard Time' when 'Australia/Melbourne' is passed to the array. Although I attempted to use the code var winTimeZone = arr ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

What is the best way to include a component in the global React variable without using import/export in the HTML?

Is it possible to include a component in React's global variable without importing/exporting to HTML? Example //HTML <body> <div id="App"></div> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" ...

Generating identical circles using PointsMaterial and CircleGeometry

My goal is to generate circles using two different methods: By utilizing a circle sprite and drawing it with Points and PointsMaterial Using basic circle buffer geometries Unfortunately, I am facing challenges trying to align them due to the size discrep ...

What are the methods for removing the color green with CSS or JavaScript?

Is it possible to isolate only the red and blue color components in an image or text using CSS 'filter' feature? If so, can someone please provide guidance on how to do this? Thank you. ...

M.E.A.N - Suite for setting up and defining backend boundaries consisting of MongoDB, Express.js, Angular2, node.js

Seeking knowledge on how the frameworks and platforms Angular 2 and Express.js collaborate in the 'mean' approach is my main query. I am interested in understanding where the client-side ends and the server-side begins. After delving into this t ...

"Troubleshooting a Javascript guessing game that isn't functioning with a do-

I have been working on a JavaScript and HTML guessing game, but unfortunately, it's not functioning as expected with the following requirements: The game should take input from the user (three attempts allowed). After entering the number, it should c ...

How can I properly define the type for an object in Typescript where the key is a string and the value is an array of objects?

let colors = { "red" : [ { title: "red", summary : "red is ...", image : "image of red", // optional link : "https:// ..." }, { ...

npm-install fails to automatically install sub-dependencies

I'm currently working on an Angular 4 project that has specific dependencies. The project is functioning properly as it is. Now, my goal is to utilize this project in another project. I've added the original project to the package.json file (und ...

Is it possible for JavaScript to identify modifications in the HTML, like an input made with Ctrl+Shift+I?

Check out this website I'm currently working on. As a fun challenge for users, we're encouraging them to use ctrl+shift+i to manipulate the HTML and modify certain elements. Is it possible for Javascript or CSS/HTML to detect these changes? For ...