Skip to content Skip to sidebar Skip to footer

Send Validation From A Componentised ReactiveFrom Input To Another ReactiveForm

A traditional ReactiveForm you specify all inputs and add formControls and validation to those inputs on the related component HTML file. I am moving some of these inputs into thei

Solution 1:

We can inject ControlContainer inside password-input component to get access to parentFormgroup. Then we can add password form control to existing formGroup dynamically.

component.ts

import { Component, OnInit, Input } from '@angular/core';
import { ControlContainer, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'password-input',
  templateUrl: './passwordinput.component.html'
})
export class PasswordInputComponent implements OnInit {
  @Input('value') value = '';
  @Input('label') label = 'test label';
  control: FormControl;
  formGroup:FormGroup;
  constructor(private controlContainer:ControlContainer) {}

  ngOnInit() {
    const parentForm = (this.controlContainer['form'] as FormGroup);
    parentForm.addControl('password',new FormControl(this.value,[Validators.required, Validators.minLength(6)]));
    this.control = parentForm.get('password') as FormControl;
  }
}

component.html

<div class="form-group">
  <label>Password</label>
  <input type="password" [formControl]="control" class="form-control" />
</div>

Working Example


Post a Comment for "Send Validation From A Componentised ReactiveFrom Input To Another ReactiveForm"