Is it possible for ngModelChange to function with a custom form control?

Suppose I want to create a custom form control. Is it possible to achieve this?

<custom-control [ngModel]="myModelVariable" (ngModelChange)="modelHasChanged($event)"></custom-control>

I've successfully implemented [(ngModel)] with all the form controls I've developed, but I'm facing issues with detecting changes. Many users of my components require this feature, and I am curious if there is a cleaner solution without using @Output EventEmitters. It seems like there might be a mistake in my approach, or perhaps I need to rethink my strategy.

Here is an example component implementation based on my understanding:

@Component({
  selector: 'custom-control',
  providers: [
    { provide: NG_VALUE_ACCESSOR, useClass: CustomControlComponent, multi: true }
  ]
})
export class CustomControlComponent implements ControlValueAccessor {

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  private innerValue: any;

  get value(): any {
    return this.innerValue;
  }

  set value(val: any) {
    if (val !== this.innerValue) {
      this.innerValue = val;
      this.onChangeCallback(this.innerValue);
    }
  }

  writeValue(val: any) {
    if (val !== this.innerValue) {
      this.innerValue = val;
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

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

}

Answer №1

Upon further examination, it became apparent that certain elements were not triggering the onChangedCallback in the setter function, leading to the issues we encountered. Additionally, there were implementation errors with other components.

We apologize for any inconvenience caused, dear Angular world.

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

issues with re-invoking the button following dynamic addition/removal in Angular 2+

A textbox with add (+) and delete (-) buttons attached horizontally has been created. The first button lacks a delete section. Its image is - https://i.sstatic.net/lwco5.png Due to coding dependency, the add (+) button disappears after the first addition. ...

What is the design for headers in accordion-groups with ngx-bootstrap?

Is there a way to customize the style of ngx-bootstrap accordion headers? I've attempted various methods, including copying and pasting code from the documentation for header customization. However, it hasn't been successful. When inspecting the ...

A TypeScript method for accessing deeply nested properties within an object

I'm currently working on a function that utilizes typings to extract values from a nested object. With the help of this post, I managed to set up the typing for two levels successfully. However, when I introduce a third (known) level between the exis ...

What are some ways to determine if the current tab is the sender of a message in the Broadcast Channel API?

In my Angular application, I am looking to utilize the Broadcast Channel API to ensure that the logged-in state is maintained across different tabs. However, the tab where the user logs in requires a slightly different code execution compared to the othe ...

How can you consistently emphasize data points in a line chart using NGRX?

I'm currently working with a line chart that displays line series. Is there any way to ensure all data points are highlighted at all times? Right now, the only time a data point is highlighted is when the mouse hovers over it. <ngx-charts-line ...

When updating data, the cursor in Angular 2 textboxes tends to move to the end of the

I have specific restrictions in the name field that I am attempting to validate using a directive. Within the directive, I am utilizing a regular expression to verify a valid name and then updating the textbox with the valid name using valueAccessor.writeV ...

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

The karma Jasmine test failed to invoke the async callback within the timeframe set by the jasmine.DEFAULT_TIMEOUT_INTERVAL

I am facing an issue with my Angular4 unit tests using karma/jasmine. When I run the tests on PhantomJS browser locally, everything works fine. However, when I attempt to run the same tests on Jenkins (on PhantomJS), I encounter the following error: Stack ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...

The export of 'User' is missing in the Msal.js file located at node_modules/msal/lib-commonjs/index

Currently, I am attempting to utilize Msal.js version 0.1.3 within an Angular application, but I am encountering the following error: ERROR in C:/Users/blah/source/repos/myapp/src/app/shared/authentication.service.ts (63,28): Namespace '"C:/Users ...

What is the best way to hold out for a specific number of promises to be fulfilled and halt the resolution of any others

While working in TypeScript, I need to create around 100 instances of Promise. However, I am only interested in waiting for the resolution of 5 of them. Any promises beyond that can either be canceled (if feasible) or rejected since they are no longer requ ...

"Stuck in a limbo during npm installation: zone.js extraction process

My expertise is not in JS, so I could use some help with this issue. I'm experimenting with the .Net Core Angular SPA template. Every time I attempt to run the npm install command, it gets stuck at the extract:zone.js step. Here's what the output ...

Step-by-step guide to initializing data within a service during bootstrap in Angular2 version RC4

In this scenario, I have two services injected and I need to ensure that some data, like a base URL, is passed to the first service so that all subsequent services can access it. Below is my root component: export class AppCmp { constructor (private h ...

Issue with Angular Router: unable to retrieve route parameters in child paths

Within our main app.component routing, we have the following setup: { path: 'store', loadChildren: './store/store.module#StoreModule', canActivate: [LoginGuard] }, Then, in the module, our routes are defined as follows: const routes: ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

TypeScript: additional information on the properties of an interface

Attempting to develop a framework that enables meta on interface fields. Consider the following example: function path(path) {} interface ITwoProps { @path('some/path') stringProp: string; @path('different/path') boolProp: boolean ...

Unexpected behavior: Axios post still enters catch block despite successful completion of Rest API call

Having an issue with my axios post request not returning the value from the API in a non-success scenario (401 error). It works fine for successful scenarios. When using Postman to test the output of my reset password API by providing an incorrect current ...

Issue encountered while developing custom Vuejs + Typescript plugin

In my index.ts and service plugin files, I have this structure: https://i.sstatic.net/Oh3Gq.png service.ts declare interface Params { title: string; description?: string; type?: string; duration?: number; } export default class ServiceToast { ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

Angular 4 Form remains valid even when an incorrect value is entered

Within my Angular 4 project, I encounter the issue of controlling input fields in multiple forms. Specifically, I need a mechanism to disable the save button if the input value is incorrect. For example, when I require an input field to only accept positi ...