I want to update input field by given name or id value with ts method with its id or name given with string.
I try diferent options with update ngModel ngValue but thats not it.
So i have an ipnut field
<div >
<input type="text" id="yproduct" name="yproduct" ngModel required>
</div>
And i change its value form service with:
this.stockInfoService.caller.subscribe(
data => {
this.caller = data
document.getElementById(this.caller).value = this.codeScan;
}
);
Everything works on html side and the field value shows inside input, but when i submit the form i have empty yproduct value !
{yproduct: ''}
CodePudding user response:
Note : you should never have to call document.getElementById
in Angular. If you end up manually using document
at all, you probably have a design flaw.
[(ngModel)]
enables to do some double data binding between a typescript variable and an <input>
.
Correct usage is :
Typescript
foo = 42
HTML
<input [(ngModel)]="foo">
Then, on backend call, you would just have to modify the foo
value and it would be reflected in the input
That being said, your main problem comes from the fact that you want to modify a field that is dynamically chosen by the backend. In order to do that, you can create multiple variables with a big switch case. That is easy, that would work but the code would be messy.
I would rather bind all <input>
to different attributes of a data
object :
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>
And on backend call, you just have to modify the right data attribute :
TypeScript
callBackend() {
this.fakeService().subscribe((resp) => {
this.data[resp] = this.codeScan;
})
}
See StackBlitz here