0

I want to update the form value from the child component. Here is the parent component:

app.component.ts

ngOnInit() {
  this.form = this.fb.group({
     priority: [this.editPriority, Validators.nullValidator],
     . 
     .
     .
  });
 }

app.component.html

  <div *ngIf="editType === 'priority'">
    <app-child[form]="form"></app-child>
  </div>

child.component.ts:

export class ChildComponent implements OnInit {
  @Input() form: FormGroup;
  constructor() { }

  ngOnInit(): void {
  }

}

child.component.html:

  <div class="col-sm-2">
    <label for="priority"> Priority</label>
  </div>
  <div class="input-group col-sm-10">
    <input type="text" class="form-control" id="priority" name="priority" formControlName="priority"
           placeholder="priority">
  </div>

I tried like this stackBlitz but I got the below error:

TypeError: Cannot read properties of null (reading 'addControl')

I tried adding:

this.form.addControl('priority', new FormControl());

inside ngOnInitbut still I got the error.

Any suggestions for updating data through the child component?

Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81

1 Answers1

0

Farzan. I use Angular event emitters, where the child calls a function in the parent (or vice-versa) when needed. This function exists in the parent or child and is called when needed, including the ability to pass parameters. Not sure if it works for your situation, but I know it works quite well for me very often.

Here is a simple example: Pass Event from child component to parent component Angular 5

Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81
DanielG
  • 1,669
  • 1
  • 12
  • 26
  • this is a general way to pass data between parent and child. in this case, the form has more than 10 fields including the priority field. so for every data changing, I should emit data that is not the best way to communicate. The more important thing is I gave the error I mentioned even before changing data. – Farzan Najipour Oct 14 '21 at 15:29