Angular form.controls [' InputName']。value更新问题

时间:2018-03-06 02:25:23

标签: angular

我在使用以下示例更新表单值时出现问题:

component.html

<form #testForm="ngForm">
    <select name="dropdown" [(ngModel)]="dropdown" (ngModelChange)="onDropdownChange($event)">
        <option value="0"></option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</form>

component.ts

export class TestComponent {
    @ViewChild('testForm') public form: NgForm;

    public dropdown: string;

    public onDropdownChange() {
        console.log("this.dropdown: " + this.dropdown);
        console.log("this.form.controls[dropdown].value: " + this.form.controls['dropdown'].value);
    }
}

页面加载时,下拉列表为空白。如果我选择&#34; 1&#34;,则会记录以下内容:

this.dropdown: 1

this.form.controls[dropdown].value: undefined

如果我然后选择&#34; 2&#34;,则会记录以下内容:

this.dropdown: 2

this.form.controls[dropdown].value: 1

我的问题是为什么会发生这种情况,我怎样才能使this.form.controls [&#39; dropdown&#39;]。值具有最新值并且不是&#39;# 34;一个落后&#34;?

2 个答案:

答案 0 :(得分:1)

尝试将(ngModelChange)更改为(change),如下所示:

<form #testForm="ngForm">
    <select name="dropdown" [(ngModel)]="dropdown" (change)="onDropdownChange($event)">
        <option value="0"></option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</form>

答案 1 :(得分:1)

另一个选择是尝试一个简单的getter / setter。

<强>模板

<form #testForm="ngForm">
    <select name="dropdown" [(ngModel)]="dropdown">
        <option value="0"></option>
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</form>

请注意,它没有modelChange或更改事件

<强>组件

export class TestComponent {
    @ViewChild('testForm') public form: NgForm;

    private _dropdown;
    get dropdown(): string {
       return this._dropdown;
    }
    set dropdown(value: string) {
        this._dropdown = value;
        console.log("this.dropdown: " + this.dropdown);
        console.log("this.form.controls[dropdown].value: " + this.form.controls['dropdown'].value);
    }
}

每次下拉值更改时都会调用setter。