Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-fill input text boxes from query params on Angular 2

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?

like image 375
Stathis Ntonas Avatar asked Dec 08 '22 20:12

Stathis Ntonas


1 Answers

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>
like image 56
Nikhil Shah Avatar answered Dec 10 '22 11:12

Nikhil Shah