Home > Software design >  Angular - input wrapped in custom component not working in template driven form
Angular - input wrapped in custom component not working in template driven form

Time:10-22

Just like the title says, if I wrap an input in my custom component, it's not being picked up by Angular's template form. Here's the enter image description here

CodePudding user response:

Need to implement ControlValueAccessor for the CustomTextBoxComponent like below:~

import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-textbox',
  templateUrl: './custom-textbox.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomTextboxComponent),
      multi: true,
    }
  ],
})
export class CustomTextboxComponent implements ControlValueAccessor {
  @Input() customValue: string = '';

  propagateChange = (_: any) => {};
  public onTouched: any = () => {};

  writeValue(obj: any): void {
    this.customValue = obj;
  }

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

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

  onModelChange(val: any) {
    this.propagateChange(val);
  }
}

Working Stackblitz

  • Related