【问题标题】:Dynamic social links in Angular 8 using Reactive FormsAngular 8 中使用响应式表单的动态社交链接
【发布时间】: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 控件以进行更改并重新映射值,但这似乎是多余的。

Stackblitz

提前致谢!

【问题讨论】:

    标签: angular angular-reactive-forms reactive-forms


    【解决方案1】:

    例如 socialLinks 是一个数组 - 您需要用 FormArray class 反映它,并且数组的项目将是 FormGroup 实例。我们可以使用现有的表单构建器来实现它,只需映射链接:

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

    在这一步之后,我们将拥有代表 socialLink 结构的 for groups 的表单数组,这就是为什么我们还需要更改 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]

    【讨论】:

    • 完美!是的,我尝试了一些变体,但看起来我错过了表单数组中的fb.group()。有时反应式表单可能会很烦人,因为它们很有用 :) 谢谢!
    • 乐于助人:)
    猜你喜欢
    • 2020-02-27
    • 2020-09-23
    • 2020-04-03
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多