Angular - Adding/removing class inside control value accesor

143 Views Asked by At

I have a reactive form with bootstrap in this way:

<form [formGroup]="form">
   <div class="mb-3">
      <label for="user">Username</label>
      <input type="text" class="form-control" id="user" placeholder="Insert Username"
        formControlName='user' [ngClass]="{'is-invalid': form.get('user').invalid && (form.get('user').touched || form.get('user').dirty), 'is-valid': form.get('user').valid}" >
   </div>
</form>

And with a custom component using control value accesors turns to:

<form [formGroup]="form">
  <custom-input formControlName="user"></custom-input>
</form>

How can i apply the [ngClass] part inside the custom input if the control is outside?

This is my custom.component.ts:

@Component({
  selector: 'custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputTextComponent),
      multi: true,
    },
  ],
})
export class InputTextComponent implements ControlValueAccessor {
  private onChangeFn: Function;
  private onTouchFn: Function;

  @Input() field: any;
  public valueInput: any;
  public disabled: boolean;
  ngControl: NgControl;

  constructor(private inj: Injector) {}

  writeValue(value: any): void {
    this.valueInput = value;
  }
  registerOnChange(fn: any): void {
    this.onChangeFn = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouchFn = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  changeText(event) {
    this.valueInput = event.target.value;
    this.onTouchFn();
    this.onChangeFn(this.valueInput);
  }
}

and my html

<div class="mb-3">
    <label for="user">Username</label>
    <input type="text" class="form-control" id="user" placeholder="Insert Username"
        [value]="valueInput" (change)="changeText($event)">
</div>
0

There are 0 best solutions below