0

I am using angular 5

In my html I generate the value of a input field using

<input type="number" class="form-control" id="unitCost" name="unitCost"    [(ngModel)]="unitCost" placeholder="Average Unit Price">
document.getElementById("unitCost").value = avgVal;

then I want to retrieve that generated value in my component.ts using

this.unitCost = form2.value.unitCost;

But it returns null value. instead if I type any value in the text field it works fine and returns the value I typed. Can I solve this issue?

3
  • 1
    Did you use the FormControl in your .ts file ? Commented Jun 19, 2018 at 11:14
  • Please don't use same word for id, name and model. Answer to your question is, this.unitCost will itself have value, because ngModel contains value and it's two way binding. Commented Jun 19, 2018 at 11:14
  • Don't mix Jquery with Angular and as a matter of fact you are already using 2 way data binding [(ngModel)]="unitCost" does not it take care of your requirements. Commented Jun 19, 2018 at 12:18

2 Answers 2

1

the best way to achieve what you want is

<input type="number" class="form-control" id="unitCost"  [(ngModel)]="unitCost" placeholder="Average Unit Price">

now in your component class you will have a variable called unitCost and you can get or set the value of the text field like this

setting value - unitCost = 'value' gettingValue - unitCost

let me know if this is clear or i will create an example for you

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

2 Comments

I am sorry! I don't get it. can you explain it a bit
here is an example I created please look at the app.component.ts and app.component.html stackblitz.com/edit/…
0

Use [ngValue] directive of angular.

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.