logo
down
shadow

Is it possible to extend DefaultValueAccessor?


Is it possible to extend DefaultValueAccessor?

Content Index :

Is it possible to extend DefaultValueAccessor?
Tag : angular , By : orneka
Date : November 28 2020, 11:01 PM

it fixes the issue With some newer angular version it is possible to extend the DefaultValueAccessor and register the value accessor without any problems.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to extend a javascript object to include a method using _.extend or $.extend?


Tag : javascript , By : Matthew Steed
Date : March 29 2020, 07:55 AM
Any of those help For example using Underscore library, the following code works: , Remove the extra );
var myobject = {};
_.extend(myobject, { 
  method: function() {
    return 'demo'
  } // ); <-- remove this
});

Angular2 No provider for Renderer! (NgModel -> Token NgValueAccessor -> DefaultValueAccessor -> Renderer)


Tag : angular , By : Nickolas
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I custom modal of customModal.ts in shlomiassaf/angular2-modal. Specific, i add a input contain ngModel, it imported FORM_DIRECTIVES and directives. , I see two possibilities:
    import {Component,Renderer,ElementRef} from 'angular2/core';

    @Component({
      selector: 'child',
      template: '<div></div>',
    })
    export class ChildComponent {
      constructor(private _renderer: Renderer,
               private el: ElementRef) {
        (...)
      }
    }
var otherResolved = Injector.resolve([
  provide(DialogRef, { useValue: dialogRef})
  provide(Renderer, { useValue: this.renderer})
]);

Implement DefaultValueAccessor won't trigger "registerOnChange"


Tag : angular , By : glisignoli
Date : March 29 2020, 07:55 AM
Does that help You need to implement a custom ControlValueAccessor instead of extending an DefaultValueAccessor. https://github.com/angular/angular/issues/9146#issuecomment-241191899
To implement ControlValueAccessor you should provide NG_VALUE_ACCESSOR token for this directive. The simplest solution could look like this:
import { 
  Input, forwardRef, Renderer2, 
  Injector, ElementRef, Directive
} from '@angular/core'

import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';

export const PREV_VAL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => PrevValDirective),
  multi: true
};

@Directive({
  selector: '[ngModel][prevVal]',
  host: {
    '(input)': 'handleInput($event.target.value)',
    '(blur)': 'onTouched()',
  },
  providers: [PREV_VAL_VALUE_ACCESSOR]
})
export class PrevValDirective implements ControlValueAccessor {
  @Input() prevVal: string;

  onChange = (_: any) => {};
  onTouched = () => {};

  constructor(
    private _renderer: Renderer2, 
    private _elementRef: ElementRef, 
    private _inj: Injector) {
  }

  writeValue(value: any): void {
    const normalizedValue = value == null ? '' : value;
    this._renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
  }

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

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

  setDisabledState(isDisabled: boolean): void {
    this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
  }

  handleInput(value: any): void {
    if (value === this.prevVal) {
      let model = this._inj.get(NgControl);  // get NgModel
      model.control.setValue(model.value);   // set previous value
      return;
    }
    this.onChange(value);
  }
}
let model = this._inj.get(NgControl);
<input type="text" [(ngModel)]="val" prevVal="false">

For custom form components, is it possible to use DefaultValueAccessor instead of ControlValueAccessor?


Tag : angular , By : yossi
Date : March 29 2020, 07:55 AM
it should still fix some issue One possible solution could be using ngDefaultControl attribute on your custom component:
<div [formGroup]="form">
    <jg-search formControlName="x" ngDefaultControl></jg-search>
                                   ^^^^^^^^^^^^^^^^
</div>
@Component({
  selector: 'jg-search',
  template: `
   <input [formControl]="ngControl.control">
  `
})
export class MyInput {
  constructor(public ngControl: NgControl) {}
}

TypeError: Class constructor DefaultValueAccessor cannot be invoked without 'new'


Tag : angular , By : Val
Date : March 29 2020, 07:55 AM
should help you out I've resolved by making the class implements ControlValueAccessor instead of extends DefaultValueAccessor.
As a consequence of that, I also had to implement the missing methods, so I added the following:
import { ControlValueAccessor } from "@angular/forms";
// ...

export class MyClass implements ControlValueAccessor {

  // ...

  onChange = (_: any) => {};
  onTouched = () => {};

  // ...

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

  setDisabledState(isDisabled: boolean): void {
    this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
  }
}
Related Posts Related QUESTIONS :
  • Angular error when changing font color from API value
  • Angular | How do i show an object inside the form of another component
  • Angular - generate array of objects and display the data
  • How to load component into another
  • Set Node options when running with Angular-CLI
  • View does not update when calling function from other component Angular + NativeSript(6)
  • The fields in my form are not binding to the model attributes in Angular
  • Can someone help me out here, can't get the routing to work properly, keep getting 404
  • Providing/Injecting third party service to component while angular component unit testing
  • Using Reactive Forms to send value from field wrapped in compulsory object
  • how to get http response from typescript post
  • how to get public IP in Angular Project
  • Access Nested Models from function Angular
  • Angular 7 - Set the data source for the Select/dropdown box
  • Angular Material Dialogue issue - Error: The selector "dialog-result-example-dialog" did not match any element
  • BodyParser doesn't parse - but everything looks right to me. How to resolve `Cannot read property of undefined`
  • Deep Linking with IOS and Android Nativescript
  • Angular 8 + IE 11: Some polyfills are missed
  • How access form attributes from component?
  • Pass all FromGroup control values to another FormGroup
  • In Angular 7, how do I access the component that emitted an event?
  • Not able to call a method when a feature/marker is selected in OpenLayers
  • How to Implement Nested NG If else conditions in Angular 8
  • Want only single true or false value from observers
  • How to add react custom element in angular 6
  • StaticInjectorError(AppModule)[MainComponent -> MatDialog]
  • Loop through data set showing undefined
  • Why does the Angular Material table mat-paginator pagesize not work?
  • Can Web API get input from angular client for confirmation and continue execution?
  • Will the angular build include the spec file size?
  • Meta tags angular 7
  • Can't find file on stackblitz Angular project
  • AngularFire Auth exchange FireBase token for my platform's token before re-direct
  • Angular 8 Component / Service: How to retrieve data from async function in service
  • Add a control to a dynamic Angular reactive form
  • Looking to Add Role-Based Authentication System
  • Angular 7/8, 1 dependency is interfering with another one, How to avoid the loading of a deep dependency while inside a
  • Compiler errors (resolving) when compiling after addition of Firebase Admin SDK
  • wrapper observable event on top of http call
  • Nginx container does not send requests to back-end
  • ngOnInit starts before APP_INITIALIZER is done
  • How to trigger a data service call in Angular
  • Where do I declare my external service in my app.module.ts file?
  • event propagation cdk drag
  • use argument as object property in angular
  • How to create new object in redux selector and return it
  • How can I show my own text status before i switch my toggle button while using mat-slide-toggle
  • Get the API response and store the data in to an array
  • How to obtain previous and new value from Angular mat-select?
  • Send payload data with POST/PUT/PATCH requests to Sentry.io
  • Angular 8 not working in IE 11 and Safari browser
  • How to create function name from json in Angular 7
  • Im trying to push values from an array with objects to another array with objects
  • Got an error when I add "changeDetectionStrategy" to my app
  • Angular typescript object undefined at start leading to undefined error
  • Failed: Template parse errors: There is no directive with "exportAs" set to "bsDatepicker" while run
  • Error: Can't resolve all parameters for setupPlatform: (?, [object Object], [object Object])
  • Differences between ng build and ng build --watch
  • Does an angular component ever destroy when it is subscribed to router change event once?
  • How do I get the JSON response from httpModule.get?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com