Issue
I've ran into some trouble setting the value of an input element using Angular.
I'm trying to set the value of dynamically created input elements in my application by this method:
copyPricingToAll(): void {
var copyValue: string = document.getElementById("priceInputGlobal").value;
this.currentItem.orderLines.forEach(orderLine => {
document.getElementById("priceInput-" + orderLine.id).setAttribute("value", copyValue);
});
}
I'm creating the rows like this:
<ng-container *ngFor="let orderLine of currentItem.orderLines let i=index">
<tr>
<td>{{getCorrectTimeString(orderLine)}}</td>
<td>{{orderLine.quantity}}</td>
<td><input id="priceInput-{{orderLine.id}}" type="number" value="{{orderLine.price}}"></td>
</tr>
</ng-container>
Unfortunately .value is not recognized as a valid operation. I'm not sure how to correctly set the value of a dynamically created element in angular. I hope someone is able to help me out with this issue.
Solution
You should use the following:
<td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>
You will need to add the FormsModule
to your app.module
in the inputs
section as follows:
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule
],
..
The use of the brackets around the ngModel
are as follows:
The
[]
show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.The
()
show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.The
[()]
are both (e.g. a two way binding)
See here for more information: https://angular.io/guide/template-syntax
I would also suggest replacing id="priceInput-{{orderLine.id}}"
with something like this [id]="getElementId(orderLine)"
where getElementId(orderLine)
returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1
in one place and priceInput-1
in another. (if you still need to access the input by it's Id somewhere else)
Answered By - William Moore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.