切换群组名称时出错

时间:2018-04-25 14:33:39

标签: angular

我有以下表格:

currentLang: string = "en-Gb";

this.myForm = new FormGroup({
    Languages: new FormGroup({
        en-Gb: new FormGroup({
            first: new FormControl('Nancy', Validators.minLength(2)),
            last: new FormControl('Drew', Validators.required)
        }),
        de-De: new FormGroup({
            first: new FormControl('Nancy', Validators.minLength(2)),
            last: new FormControl('Drew', Validators.required)
        }),
    })
});

switchLang(newLang) {
    this.currentLang = newLang;
}

这里的模板代码:

<form [formGroup]="myForm" novalidate (ngSubmit)="submit(myForm)" class="generalForm">

    <div formGroupName="Languages">
        <ol formGroupName="{{currentLang}}">
            <li>
                <label>Firstname:</label>
                <input id="first" type="text" formControlName="first">
            </li>
            <li>
                <label>Lastname:</label>
                <input id="last" type="text" formControlName="last">
            </li>
        </ol>
    </div>

</form>

<button (click)="switchLang('de-De')">Switch to German</button>

但是当我按下&#34;切换到德语按钮&#34;我的字段仍然基于&#34; en-Gb&#34;的值。如何让这些字段进入德语模式?切换语言时,我希望这些字段变为空白,以便我可以填写德语视图中的字段。

1 个答案:

答案 0 :(得分:1)

最后在这篇文章中找到了答案= Angular - formGroupName value change does not update the form

似乎在你以任何方式使formgroupname动态化的那一刻,你必须修改特定于该对象的字段(如果它是静态的则不是这种情况)。在我的情况下,我不得不将字段更改为:

<input id="first" type="text" [formControl]="myForm.controls['Languages'].controls[currentLang].controls['first']">
<input id="first" type="text" [formControl]="myForm.controls['Languages'].controls[currentLang].controls['last']">