0

I am in a process of designing a form which has some repeated complex logic. I am using reactive forms approach for the same. Since the logic is repeatative, i thought of creating a component for the same. below is the call from parent form.

<ms-diag [parentForm] = "SOForm"></ms-diag>

I am passing the parent form as an input to the child component. But I am receiving undefined as output in child component

  @Input() parentForm : FormGroup;  

  constructor() {
   this.text = 'Hello World';
   console.log('New Value >>>>>>>>>>>>>>>>>>>>');
   console.log(this.parentForm);
  }

am i missing something here?

mulla.azzi
  • 2,676
  • 4
  • 18
  • 25
  • you can use a setter in the Input,e.g. _parentForm:any;@Input set parentForm(value){this._parentForm=value;..here you has value..} //remember referer in your .html to the variable _parentForm, not parentForm – Eliseo Jan 14 '19 at 14:19

1 Answers1

2

@Input properties are not available in the constructor. They are available in the ngOnChanges. So move your constructor code to ngOnChanges and it should work. Something like this:

@Input() parentForm: FormGroup;

constructor() {...}

ngOnChanges() {
  this.text = 'Hello World';
  console.log('New Value >>>>>>>>>>>>>>>>>>>>');
  console.log(this.parentForm);
}

PS: This in no way imply that you should initialize your Component properties inside ngOnChanges. You should do it inside the ngOnInit method.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • 1
    I downvoted, because this answer implies that `ngOnChanges` is where the OP should move his initialization code. Which is risky advice and doesn't explain that it will be executed multiple times or why. There are also other hooks where he could initialize his logic. So this is misleading. Please update the answer and I'll correct my vote. – Reactgular Jan 14 '19 at 13:30
  • @cgTag, thanks a lot for the downvote and the also for the reason. Really appreciate it. I've updated the answer with a comment. Hope that addresses your concern. :) – SiddAjmera Jan 14 '19 at 16:37