I have a form in a seperate component which looks like this:
<form [formGroup]="form">
<div class="card" style="margin-bottom: 10px" >
<input
formControlName="name"
type="text"
placeholder="please enter"
/>
</div>
</form>
the ts file looks like this (formcontrol part)
form = this.builder.group({
name: new FormControl(),
})
this is how I call it from the other component: component B:
<form></form>
What I want to achieve now is the following I am filling some values from my backend which works, I know want to asign these values to my form from the form component. I know I have to use @Input I am kinda stuck against a wall and dont know how to connect them. Can someone give me a small example how I can fill my form from values from component b?
To my knowledge I have posted the most important part of this question, if anything else is needed feel free to ask
UPDATE_ Form.ts
@Input()
myObject: { name: string };
form = this.builder.group({
name: new FormControl()
});
ngOnChanges(changes: SimpleChanges): void {
if (changes.myObject?.currentValue) {
this.form.patchValue(this.myObject);
}
}
UPDATE2:
my form ts looks like this now:
@Input()
myObject: { name: string };
form = this.builder.group({
name: new FormControl()
});
ngOnChanges(changes: SimpleChanges): void {
if (changes.myObject && changes.myObject.currentValue) {
this.form.patchValue(this.myObject);
}
}
My form.hml like this:
<form [formGroup]="form">
<div class="card" style="margin-bottom: 10px" >
<input
formControlName="name"
type="text"
placeholder="please enter"
/>
</div>
</form
my calling component ts like this:
this.form.controls.legitimiertePersonNameField.setValue(response.vorname)
this.someName = this.form.controls.legitimiertePersonNameField.value -> gets the data from formcontrol in parent/calling
html from caling looks like this:
<gwg-form [myObject]="someName"></gwg-form>
The someName value is correct I could see it in a console.log but it does not set the value for the fomrCOntrol of the form.html it is just empty input
@Component({
selector: 'my-form'
...
})
export class FormComponent implements OnChanges {
@Input()
myObject: { name: string };
form = this.builder.group({
name: new FormControl()
});
ngOnChanges(changes: SimpleChanges): void {
if (changes.myObject?.currentValue) {
this.form.patchValue(this.myObject);
}
}
}
<form [formGroup]="form">
<div class="card" style="margin-bottom: 10px" >
<input
formControlName="name"
type="text"
placeholder="please enter" />
</div>
</form>
@Component({ ... })
export class CallingComponent {
someObject: { name: string };
loadData(): void {
this.someObject = ...
}
}
<my-form [myObject]="someObject">
</my-form>