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

Time:10-05

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:

<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),
  });
}

CodePudding user response:

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

  • Related