I'm trying to render a list of dynamic social links in my Angular app. The data comes from the database like this:
// User model
{
...
socialLinks: [
{ name: 'Site1', url: 'https://site1.com/user' },
{ name: 'Site2', url: 'https://site2.com/user' },
...
}
...
}
This is how the form group is created in the component:
public async ngOnInit(): Promise<any> {
const userResult = await this.userService.getLoggedInUser();
if (userResult) {
this.userSettingsForm = this.fb.group({
displayName: [this.user.displayName, Validators.required],
bio: [this.user.bio, Validators.maxLength(256)],
location: [this.user.location],
socialLinks: this.fb.group(this.user.socialLinks)
});
}
}
And the template:
<form [formGroup]="userSettingsForm" (ngSubmit)="submitForm()">
...
<div *ngFor="let socialLink of user.socialLinks; let index = index" formArrayName="socialLinks">
<div class="position-relative">
<img [src]='"/assets/icons/" + user.socialLinks[index].name + ".svg"'
[alt]='user.socialLinks[index].name + " page"'>
<input class="form-control" [formControlName]='index'
[value]='user.socialLinks[index].url'>
</div>
</div>
</form>
The fields are populated with the url as they should, but I'd like the form value to reflect the same structure as the data coming from the database. Currently, if I edit any of the fields, the value of the input goes from the original object to just a string. I tried subscribing to the socialLinks
controls for changes and remapping the values, but that seemed redundant.
Thanks in advance!