Pre-fill input text boxes from query params on Angular 2
NOTE
: Don't use "{{}}"
together for bindings.
1) You can either use [(ngModel)]
,
<input type="text" formControlName="name"
class="form-control" id="name"
[(ngModel)]="paramName" required>
<input type="text" formControlName="lastName"
class="form-control" id="lastname"
[(ngModel)]="paramLastName" required>
2) OR [value]
to bind property angular2 way,
<input type="text" formControlName="name"
class="form-control" id="name"
[value]="paramName" required>
<input type="text" formControlName="lastName"
class="form-control" id="lastname"
[value]="paramLastName" required>
Stathis Ntonas
Full Stack Developer Stack: React React Native Nodejs MongoDB Hasura Postgresql
Updated on June 22, 2022Comments
-
Stathis Ntonas almost 2 years
I have a form on one page with 2 input boxes and when i click submit then the router navigates to another page with 2 input boxes and a submit button.
So far i've managed to pass the query params to the 2nd page and pre-filled the input boxes.
Problem is, when i hit submit button on page 2, the values from the input boxes are not submitted. If i "touch" the boxes and enter something else, then the submit works fine and the edited values are being submitted.
1st page ( i'm leaving out the rest of the code, this part works ok)
this._router.navigate(['/dashboard/test/new'], { queryParams: {'name': this.name.value , 'lastname':this.lastname.value}});
2nd page
private subscription: Subscription paramName: string; paramLastName: string this.subscription = this.activatedRoute.queryParams.subscribe( params => { this.paramName = params['name']; this.paramLastName = params['lastname']; } )
And here is the html:
<form [formGroup]="myFormTest" (ngSubmit)="onSubmitNew()" class="onl_loginForm" novalidate> <div class="form-group"> <label for="name" class="control-label">Name </label> <input type="text" formControlName="name" class="form-control" id="name" value="{{paramName}}" required> </div> <div class="form-group"> <label for="lastname" class="control-label">Last Name </label> <input type="text" formControlName="lastName" class="form-control" id="lastname" value="{{paramLastName}}" required> </div> <button type="submit" class="btn-save">Submit</button> </form>
How can i force the form to "read" the two input fields values without touching them?
-
Stathis Ntonas over 7 yearsThanks! The [(ngModel)] method worked, the [value] prefilled the input boxes but they were submitted as null (like in my code).
-
micronyks over 7 yearsYes they will not as they just bind the value. While submission form uses
formControl
. So that will not work. If you want them to work, you should use ( in TS code - I feel you are using formBuilder) something likename:[paramName , ....]
syntax.