角度2/4-将单选按钮[value]绑定到对象或函数时,为什么此反应式表单值未更新?

时间:2018-09-19 01:26:30

标签: javascript angular radio-button angular-reactive-forms reactive-forms

*注意:如果有人能更好地做到这一点,我将不知所措。

我试图用三个单选按钮创建一个表单-两个带有静态值,一个带有自定义的用户生成值。这是正在发生的事情:

我将默认值设置为一个: default set to one

当我单击两个时,一切都会按预期进行:

when I click two

当我单击“自定义”单选按钮时,一切都会按预期进行:

when I click three

当我输入一个值时,对象正确地被突变,但是表单值(设置为对象键之一)不会更新:

form value doesn't update when I enter a value in input

我可以单击回到两个并获得预期的行为:

when I click back to two I see expected behavior

然后当我单击返回三时,我看到预期的行为:

when I click back to three, I see expected behavior

这是我的代码:

test.html

<form [formGroup]="myForm" novalidate>
    <label for="every_fifteen_minutes">
        <input id="two" type="radio" formControlName="test" value="one">
        <span class="input_text">This [value] will always be one</span>
    </label>
    <label for="two">
        <input id="two" type="radio" formControlName="test" value="two">
        <span class="input_text">This [value] will always be two</span>
    </label>
    <label for="three">
        <input id="three" type="radio" formControlName="test" [(value)]="myObj.strKey">
        <span>This [value] should be set to the input value:</span>
        <input type="text" [(ngModel)]="myObj.strKey" [ngModelOptions]="{standalone: true}">
    </label>
</form>
<div>this.myObj.str: {{getThat()}}</div>
<div>this: {{getThis()}}</div>

test.component.ts

myForm: any;
myObj: any = {
    strKey: ""
}

private _buildForm() {
    this.myForm = this.fb.group({
        'test': ['1', Validators.required],
    })
}

ngOnInit() { 
    this._buildForm();
}

getThat(): number {
    return this.myForm.get('test').value
}

getThis(): string {
    return this.myObj.strKey;
}

所以,我的问题是:为什么更新不是立即发生,如何使它发生,并且有可能以一种不太复杂的方式进行?

1 个答案:

答案 0 :(得分:0)

尝试在

中添加(输入)=“ 0”
<input id="three" type="radio" formControlName="test" [(value)]="myObj.strKey">

像这样

<input id="three" type="radio" formControlName="test" [(value)]="myObj.strKey" (input)="0">