Angular 更改为 typeescript 输入字段值在提交时为空
Angular changed with typeescript input field value empty on submit
我想用 ts 方法更新给定名称或 id 值的输入字段,其 id 或名称用字符串给出。
我尝试使用更新 ngModel ngValue 的不同选项,但事实并非如此。
所以我有一个 ipnut 字段
<div class="col-auto">
<input type="text" id="yproduct" name="yproduct" class="form-control" ngModel required>
</div>
并且我将其值形式服务更改为:
this.stockInfoService.caller.subscribe(
data => {
this.caller = data
document.getElementById(this.caller).value = this.codeScan;
}
);
html 端一切正常,字段值显示在输入中,但是当我提交表单时,我的 yproduct 值为空!
{yproduct: ''}
注意:您永远不必在 Angular 中调用 document.getElementById
。如果您最终完全手动使用 document
,则您可能存在设计缺陷。
[(ngModel)]
可以在打字稿变量和 <input>
.
之间进行一些双重数据绑定
正确的用法是:
打字稿
foo = 42
HTML
<input [(ngModel)]="foo">
然后,在后端调用时,您只需修改 foo
值,它就会反映在 input
中
也就是说,您的主要问题来自于您想要修改由后端动态选择的字段这一事实。为此,您可以使用一个大的 switch case 创建多个变量。这很简单,可以,但代码会很乱。
我宁愿将所有 <input>
绑定到 data
对象的不同属性:
TypeScript
data = {
foo: 42,
bar: 51,
}
HTML
<div>Foo : <input id="foo" [(ngModel)]="data.foo" /></div>
<div>Bar: <input id="bar" [(ngModel)]="data.bar" /></div>
并且在后端调用时,您只需修改正确的数据属性即可:
TypeScript
callBackend() {
this.fakeService().subscribe((resp) => {
this.data[resp] = this.codeScan;
})
}
参见 StackBlitz here
我想用 ts 方法更新给定名称或 id 值的输入字段,其 id 或名称用字符串给出。
我尝试使用更新 ngModel ngValue 的不同选项,但事实并非如此。
所以我有一个 ipnut 字段
<div class="col-auto">
<input type="text" id="yproduct" name="yproduct" class="form-control" ngModel required>
</div>
并且我将其值形式服务更改为:
this.stockInfoService.caller.subscribe(
data => {
this.caller = data
document.getElementById(this.caller).value = this.codeScan;
}
);
html 端一切正常,字段值显示在输入中,但是当我提交表单时,我的 yproduct 值为空!
{yproduct: ''}
注意:您永远不必在 Angular 中调用 document.getElementById
。如果您最终完全手动使用 document
,则您可能存在设计缺陷。
[(ngModel)]
可以在打字稿变量和 <input>
.
正确的用法是:
打字稿
foo = 42
HTML
<input [(ngModel)]="foo">
然后,在后端调用时,您只需修改 foo
值,它就会反映在 input
也就是说,您的主要问题来自于您想要修改由后端动态选择的字段这一事实。为此,您可以使用一个大的 switch case 创建多个变量。这很简单,可以,但代码会很乱。
我宁愿将所有 <input>
绑定到 data
对象的不同属性:
TypeScript
data = {
foo: 42,
bar: 51,
}
HTML
<div>Foo : <input id="foo" [(ngModel)]="data.foo" /></div>
<div>Bar: <input id="bar" [(ngModel)]="data.bar" /></div>
并且在后端调用时,您只需修改正确的数据属性即可:
TypeScript
callBackend() {
this.fakeService().subscribe((resp) => {
this.data[resp] = this.codeScan;
})
}
参见 StackBlitz here