Search code examples
angularangular11

Angular 11 how to initialize the Child's formgroup values?


In Parent HTML have defined like this -

 <div class="modal-body">
          <app-addchild [childform]="element"></app-addchild>
 </div>

element here is the row data in JSON format, with field values.

childform is formgroup defined as @Input() with the child's Component like this -

 @Input() public childform = new FormGroup({
      code: new FormControl('', [Validators.required, Validators.pattern('[0-9]+')]),
      countryCode: new FormControl('', Validators.required),
      ...
    });

Solution

  • You can assign values to @Input like this. You can do something like this

    @Input() set childform(value) {
          // value is data passed to the input
         // you can do something like this
         this.gnpform.get('code').setValue(value.code);
    }
    
    
    public gnpform = new FormGroup({
          code: new FormControl('', [Validators.required, Validators.pattern('[0-9]+')]),
          countryCode: new FormControl('', Validators.required),
          ...
        });