Angular 12 - TypeError: no se pueden leer las propiedades de nulo (leyendo 'writeValue')
Estoy creando un componente de entrada de texto genérico, todo funciona bien mientras sirve el proyecto, pero en el proyecto construido aparece este error:
TypeError: no se pueden leer las propiedades de null (leyendo 'writeValue')
HTML:
<div class="p-field"> <label>{{label}} <span class="p-error">{{checkRequired(ngControl.control) ? '*' : ''}}</span></label> <input class="full-width" [type]="type" pInputText [formControl]="ngControl.control"> <small *ngIf="ngControl.control.touched && ngControl.control.errors?.required" class="p-error">{{label}} is required</small> <small *ngIf="ngControl.control.errors?.minlength" class="p-error"> {{label}} must be at least {{ngControl.control.errors.minlength['requiredLength']}} </small> <small *ngIf="ngControl.control.errors?.maxlength" class="p-error"> {{label}} must be at most {{ngControl.control.errors.maxlength['requiredLength']}} </small> <small *ngIf="ngControl.control.errors?.email" class="p-error"> This email is not valid </small> <small *ngIf="ngControl.control.errors?.isMatching" class="p-error">Passwords do not match</small> </div>componente.ts
import { Component, Input, OnInit, Self } from '@angular/core'; import {AbstractControl, ControlValueAccessor, NgControl} from '@angular/forms'; @Component({ selector: 'app-text-input', templateUrl: './text-input.component.html', styleUrls: ['./text-input.component.css'] }) export class TextInputComponent implements ControlValueAccessor { @Input() label: string; @Input() type = 'text'; constructor(@Self() public ngControl: NgControl) { this.ngControl.valueAccessor = this; } checkRequired(control) { if (control.validator) { const validator = control.validator({} as AbstractControl); if (validator && validator.required) { return true; } } } writeValue(obj: any): void { } registerOnChange(fn: any): void { } registerOnTouched(fn: any): void { } }Información angular:
CLI angular: 12.2.6 Nodo: 14.17.3 Administrador de paquetes: npm 6.14.13 SO: win32 x64 Angular: 12.2.6
El error ocurre cuando falta la configuración del proveedor
providers: [ { provide: NG_VALUE_ACCESSOR, multi:true, useExisting: CUSTOMER_INPUT_CLASS_HERE } ]En tu caso
@Component({ selector: 'app-text-input', templateUrl: './text-input.component.html', styleUrls: ['./text-input.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, multi:true, useExisting: TextInputComponent } ] }) export class TextInputComponent implements ControlValueAccessor { ... }Recibí este error cuando intenté realizar la verificación de autorización en la parte de back-end de la lógica de validación. Declaré el botón de enviar en el grupo de creadores de formularios. Cuando usé una entrada con style="display: none" todo estuvo bien.
En el constructor, use @Optional() y realice una verificación nula:
constructor(@Optional() @Self() public ngControl: NgControl) { if (this.ngControl != null) this.ngControl.valueAccessor = this; }Además, agregue cuerpo a métodos como
writeValue(value: number): void { this.value = value; this.onChange(this.value); } onChange: (_: any) => void = (_: any) => {}; onTouched: () => void = () => {}; registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; }