简体   繁体   English

Angular 8 中使用 Reactive Forms 的动态社交链接

[英]Dynamic social links in Angular 8 using Reactive Forms

I'm trying to render a list of dynamic social links in my Angular app.我正在尝试在我的 Angular 应用程序中呈现动态社交链接列表。 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.这些字段按应有的方式填充了 url,但我希望表单值反映与来自数据库的数据相同的结构。 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.我尝试订阅socialLinks控件以进行更改并重新映射值,但这似乎是多余的。

Stackblitz闪电战

Thanks in advance!提前致谢!

Such as socialLinks is an array - you would need to reflect it with FormArray class and items of the array would be FormGroup instances.例如socialLinks是一个数组 - 您需要使用FormArray 类来反映它,数组的项目将是FormGroup实例。 We could achieve it with an existing form builder, simply mapping over links:我们可以使用现有的表单构建器来实现它,只需通过链接进行映射:

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

after this step, we would have form array with for groups which represents structure of socialLink , so that is why we also need changes in html to cover it(from stackblitz):在这一步之后,我们将拥有代表socialLink结构的 for 组的表单数组,这就是为什么我们还需要更改 html 来覆盖它(来自 stackblitz):

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

now each [formGroupName] would be and an index and formControlName would represent the field we want to work with现在每个[formGroupName]将是一个索引formControlName将代表我们想要使用的字段

Hope this helps :)希望这可以帮助 :)

Also, there are some handy explanations here:此外,这里还有一些方便的解释:

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

When to use FormGroup vs. FormArray? 何时使用 FormGroup 与 FormArray?

PS consider using socialLink inside *ngFor such as it is the direct reference to user.socialLinks[index] PS 考虑在*ngFor使用socialLink例如它是对user.socialLinks[index]的直接引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM