Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use the @Input() of a component as initial value for an input field

If I have Component A that contains Component B is there a correct way to use the value of a @Input() property on Component B as the initial value of an input field in that component?

An example of something I tried was to pass in the value when constructing the form. But it only works if it is declared again in ngOnInit.

Component A template:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<component-b [(initialValue)]='initialValue'><component-b/>

Component B:

@Input() initialValue!: string;
public form: FormGroup;

constructor(private formBuilder: FormBuilder) {
  this.form = this.formBuilder.group({
    inputField: new FormControl(this.initialValue),
  });
}

ngOnInit() {
   this.form = this.formBuilder.group({
    inputField: new FormControl(this.initialValue),
  });
}

>Solution :

that is the main point of using ngOnInit instead of constructor.

at the moment of constructor execution the instance of a component is being created, but inputs are not bound yet. ngOnInit executes a bit later, when the inputs are bound already, but the template of a component itself isn’t executed yet.

The correct result would be to remove form creation from the constructor, and leave the one in ngOnInit

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading