Home > OS >  How do i pass the hidden value from the html page to the component in angular?
How do i pass the hidden value from the html page to the component in angular?

Time:03-24

I am trying to pass the price field as hidden to the component action using the following

<form #formValue1 = "ngForm" (ngSubmit)="submit(formValue1)" method="post">
<input type="hidden" name="price" ngModel value="10">```
 <button  type="submit">Search</button>
  </form>

But the value is not getting in the action in the component. The following are the content in the component file

 submit(formValue:any){
    var formData: any = new FormData();
    console.log("Form Submitted !",formValue.value);
 }

The price value is getting as null eventhough i set the value as 10. What may be the reason? is there any issues in setting the hidden field value?

CodePudding user response:

You might want to try with <input type="text"> before. It will make it easier to see what happens.

If you want to use ngModel, you must use the "banana in a box syntax" [(ngModel)]="myVariable" and you must bind it to a variable on TypeScript side :

HTML

<input type="text" name="price" [(ngModel)]="price" value="10">

TypeScript

price: number;

The problem is that the binding will not happen in the direction you think. The value 10 from HTML will not be reflected in the variable price.

Instead, the undefined value in the variable will be reflected in the HTML value. If you want to check, you can give a value of 10 on HTML side and a value of 20 on TypeScript side and see that the resulting value is 20

As a result, the correct syntax is :

HTML

<input type="text" name="price" [(ngModel)]="price">

TypeScript

price = 10;

CodePudding user response:

You should use the 'banana in a box' syntax on ngModel. try puting [(ngModel)] instead, then when you update the value in your html template, the variable attached to it will update as well.

  • Related