0

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 class="col-auto">
<input type="text" id="yproduct" name="yproduct" class="form-control"  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: ''}
2
  • 1
    You shouldn't use the document object, Angular should be the one handling the DOM. Also, have you tried using either Template driven forms or Reactive forms? Commented Mar 24, 2022 at 17:22
  • angular.io/guide/built-in-directives#ngModel Commented Mar 24, 2022 at 17:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.