Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]:

import { Component, Injector, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, FormGroup } from '@angular/forms';

@Component({
    selector: 'time-picker',
    template:
        `<input type="text" class="clockpicker" [formControl]="selectedTime" />`,
    providers: [{
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => TimePickerComponent),
        multi: true,
    }]
})

export class TimePickerComponent implements OnInit, ControlValueAccessor {
    
    selectedTime = new FormControl('');

    constructor() { }

    ngAfterViewInit() {
        this.scriptLoader.load(
            'assets/clockpicker/clockpicker.js'
        );
    }
 
    writeValue(obj: any): void {
        if (this.selectedTime) {
            this.selectedTime.setValue(obj);
        }
    }

    registerOnChange(fn: any): void {
        this.selectedTime.valueChanges.subscribe(fn);
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }

}

In the code above, I have imported an external JavaScript library named clockpicker.js. This library is used for creating a simple clock picker feature. Here's the script for it:

$(document).ready(function () {
    $('.clockpicker').each(function (index, element) {
        $(element).clockpicker({
            afterDone: function () {
                $(element).find('input[type="text"]').change();
            }
        });
    });
});

The issue here is that when I manually input text into the field, I can retrieve the value inserted via [(ngModel)]. However, when the clockpicker function populates the field with a value, I cannot access that filled value using [(ngModel)]. This problem arises because the registerOnChange event in Angular lifecycle does not get triggered even when I use

$(element).find('input[type="text"]').change();

No action is taken as a result.

Answer №1

Angular is unaware of changes occurring outside its zone, so it's important to notify your Angular app when a change detection cycle needs to be run in order to identify any updates that need to be made.

In this scenario, make sure to initialize the clock-picker within your component and detect changes using ChangeDetectorRef. Also, consider learning more about NgZone, which can help execute tasks that are outside of the Angular zone.

Additional Resources:

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

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

How can I use a button created with jQuery's .html() method to conceal a <div>?

I am facing an issue with implementing a simple banner that should appear in an empty element only when specific values are returned by an Ajax call. In the banner, I want to include a Bootstrap button that hides the entire div when clicked. Due to my la ...

What is the process by which a JavaScript Date object is converted to a string when you log it to the

Whenever I create objects in JavaScript and output them to the console, I typically see a JavaScript object displayed. For instance: var myObj = { bla: "foo" } console.log(myObj); This code will display: { bla: "foo" } However, whe ...

Discovering Angular 2 Service Change Detection

Exploring the Angular 2 beta has led me to some challenges with understanding the change detection mechanism. I have put together a simple Plunker example that demonstrates an issue I am encountering. //our root app component import {Component, Injectab ...

Managing the verification of data existence in the ExpressJS service layer or controller

Working on a medium-sized website, I realized the importance of writing maintainable code with a better project structure. After stumbling upon this insightful article and some others discussing the benefits of 3-layer architecture, I found the concept qu ...

Running Handlebars using NodeJS can sometimes result in a "Cannot find module './parser'" error

After successfully creating and implementing a Handlebars template in the Browser, my next goal is to utilize the Handlebars precompiler, which requires a NodeJS module. I have already downloaded Handlebars for NodeJS along with all dependencies locally (n ...

Data is not appearing when using Node.js with mongoose and the populate() method

I am facing an issue while trying to display data from a database. Even though I have integrated 3 different schemas into one, the combined data is not being displayed as expected. I have attached all three schemas for reference. While async-await along w ...

Keep sending HTTP requests until the header contains an attachment

Welcome to our web application where you can generate and download a .zip file simply by visiting the URL. I am looking to develop a Node.js application using the requestjs library that will continuously send requests until it detects an attachment header ...

If the variable is empty, use jQuery ajax to send a request with different data

Below is the code I have written: $(document).ready(function() { cookieanimalid =($.cookie("cookieanimal")); $.ajax({ type: 'POST', url: "/myurl/", data: {cookieanimalid}, success: function ( ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

Achieve instant redirection upon user logout with Angular and Meteor

Within a Meteor application utilizing Angular, there exists a specific state that mandates the user to be logged in. Currently, this requirement is implemented using $meteor.requireUser() function run($rootScope, $state) { $rootScope.$on('$state ...

``There appears to be an issue with the functionality of the jQuery

I've been experimenting with using AJAX in a PHP form, but for some reason it's not working as expected. I'm at a loss trying to figure out why. Here is my code: <!DOCTYPE html> <html lang="es"> <head> <title>< ...

Error message: NestJS encountered a problem with Neovim due to an import prefix missing and the inability to load a local module

This issue can be frustrating as it doesn't affect the functionality of the program. However, upon opening a new or existing NestJS application, all imports are highlighted as errors. For instance, in the main.ts file, there are two imports: import { ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

The type '{ domain: string; parent: string; }' cannot be assigned to type 'string'. Error code: ts(2322)

Hello there! I am new to TS, so thank you for taking the time to read this. The problematic line in my code is: <this.RenderPostLink domain={r.domain} parent={r.parent} /> where I encounter an error. RenderImages = (): React.ReactElement => ...

Issue: The specific module is unable to be located, specifically on the Heroku platform

While my application performs well locally and on a Travis CI build server, it encounters issues when deployed on Heroku. The error message Error: Cannot find module is displayed, leading to app crashes. Here are some details about the npm module: It r ...

In AngularJS expressions, you can compare two dates and use ng-hide based on the comparison

Is it possible to compare two Date strings using Angular JS Expressions? HTML <body ng-controller="app"> <div>{{Today}}</div> <div>{{ItemDate}}</div> <div>{{ItemDate<Today}}</div> </body> ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

What does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...

Problem encountered when attempting to return data received from database queries executed within a loop

Having an issue with making multiple MongoDB queries in a loop and trying to send all the results as one data array. However, simply using 'return' to send the data is resulting in 'undefined' and not waiting for the results of all DB r ...