gpt4 book ai didi

angular - Angular 8 中使用响应式(Reactive)表单的动态社交链接

转载 作者:行者123 更新时间:2023-12-02 10:30:18 26 4
gpt4 key购买 nike

我正在尝试在我的 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,但我希望表单值能够反射(reflect)与来自数据库的数据相同的结构。目前,如果我编辑任何字段,输入的值将从原始对象变为字符串。我尝试订阅 socialLinks 控件进行更改并重新映射值,但这似乎是多余的。

Stackblitz

提前致谢!

最佳答案

例如 socialLinks 是一个数组 - 您需要用 FormArray class 来反射(reflect)它数组的项将是 FormGroup实例。我们可以使用现有的表单生成器来实现它,只需映射链接即可:

socialLinks: this.fb.array(this.user.socialLinks.map((l) => this.fb.group(l)))

在此步骤之后,我们将拥有代表 socialLink 结构的组的表单数组,因此这就是为什么我们还需要更改 html 来覆盖它(来自 stackblitz):

<div class="position-relative" [formGroupName]='index'>
...
<input class="form-control" formControlName='url'>
</div>

现在每个[formGroupName]将是,索引formControlName将代表我们想要使用的字段

希望这有帮助:)

此外,这里还有一些方便的解释:

https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

When to use FormGroup vs. FormArray?

附注考虑在 *ngFor 中使用 socialLink,例如它是对 user.socialLinks[index]

的直接引用

关于angular - Angular 8 中使用响应式(Reactive)表单的动态社交链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59830053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com