0

I am new to angular and trying to send values through form submit, form works fine and sends updated values if I make changes using typing-in text-boxes but if if try to change values using java-script it does not detect the updated values. Please help

<form  #mapFrm = "ngForm" (ngSubmit) = "onClickSubmit(mapFrm)" >
 <input type="text" class="form-control" ngModel    name="lat" required />
</form> 

Example: https://stackblitz.com/edit/angular-1ehuzw

4

3 Answers 3

3

From the HTML code you've provided it looks like you're using Template-driven forms

With template driven forms, two-way data binding is the recommended way to set the value in the form.

<form  #mapFrm="ngForm" (ngSubmit)="onClickSubmit(mapFrm)" >
 <input type="text" class="form-control" [(ngModel)]="yourLatValue" name="lat" required />
</form> 

Where yourLatValue is a public property of the component that contains the form.

I've created this StackBlitz Demo with a working example of your code so you can play with it.

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

3 Comments

Thanks Narm for your reply but this is what I am doing: stackblitz.com/edit/angular-1ehuzw
Angular encapsulates its components so it will not be possible access the form value from outside the component like you're attempting to do with the <script> tag. In addition, and more importantly, Angular forbids the use of <script> tags in your HTML in the way that you're using it. If you try to do a production build you will find that it will fail, because <script> tags are forbidden.
Interestingly if you click his "Change Value By JS" button, the content of the input is changed, but if you click "Change value Using Angular", this new value is not shown/submitted, but the old value instead. I guess this is because of the encapsulating @Narm refers to!?
0

When you change the value using javascript, actually you are manipulating the DOM element. Which has no effect on angular value i.e yourLatValue. Since the submit method is the part of angular, so it is not working.

Ideally, you should not manipulate anything in angular from outside.

Comments

0

Agree with Lalit. You are actually changing DOM element. No matter how much changes you make in DOM. You cant get your desired values. Unless you don't make a change in your angular reactive form.

A possible work around would be calling your changeValueByJs() in the app.component.ts

changeValueByJs(){
 this.yourLatValue = "My Updated value from JS";
}

You can achieve it by using above function and you are changing it using JavaScript as well.

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.