【发布时间】:2020-05-06 20:41:18
【问题描述】:
我正在尝试在我的 Angular 应用程序中呈现动态社交链接列表。数据来自数据库,如下所示:
// User model
{
...
socialLinks: [
{ name: 'Site1', url: 'https://site1.com/user' },
{ name: 'Site2', url: 'https://site2.com/user' },
...
}
...
}
这是在组件中创建表单组的方式:
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)
});
}
}
还有模板:
<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>
字段按应有的方式填充 url,但我希望表单值反映与来自数据库的数据相同的结构。目前,如果我编辑任何字段,输入的值将从原始对象变为字符串。我尝试订阅 socialLinks 控件以进行更改并重新映射值,但这似乎是多余的。
提前致谢!
【问题讨论】:
标签: angular angular-reactive-forms reactive-forms