Reputation: 513
I'm using angular7 I tried to display values in textbox I'm getting values from backend but I dont know how to display values in textbox can anyone suggest me?
I'm using Loopback and angular7
file.component.ts
ngOnInit() {
let userId = window.localStorage.getItem("editUserId");
if(!userId) {
alert("Invalid action.")
this.router.navigate(['list-user']);
return;
}
alert(userId)
this.editForm = this.formBuilder.group({
id: [''],
name: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
age: ['', Validators.required],
salary: ['', Validators.required]
});
this.apiService.getUserById(+userId)
.subscribe( data => {
this.editForm.setValue(data);
//alert(data)
});
}
file.component.html
<div class="hidden">
<input type="text" formControlName="id" placeholder="id" name="id" class="form-control" readonly="true">
</div>
<div class="form-group">
<label for="name">User Name:</label>
<input type="text" formControlName="name" placeholder="name" name="name" class="form-control" id="name" readonly="true">
</div>
Upvotes: 1
Views: 1974
Reputation: 897
You can use the patch value API that provided for the form object!
this.editForm = this.formBuilder.group({
id: [''],
name: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
age: ['', Validators.required],
salary: ['', Validators.required]
});
this.apiService.getUserById(+userId)
.subscribe( data => {
this.editForm.patchValue({
id: data.id,
name: data.name
firstName: data.firstName,
lastName:data.lastName,
age:data.age,
salary: data.salary
});
}
Upvotes: 0
Reputation: 18973
You can use set by this.editForm .controls['firstName'].setValue(data.firstName);
Another solution you can change setValue
to patchValue
method this.editForm.patchValue(data)
;
Example:
var data= {firstName: 'Hien', lastName : 'Nguyen', email: '[email protected]'};
this.editForm .controls['firstName'].setValue(data.firstName);
this.editForm .controls['lastName'].setValue(data.lastName);
Demo:
https://stackblitz.com/edit/angular-7-reactive-form-validation-test
Upvotes: 3
Reputation: 6854
You need to bind the input value to the component property. If you can provide a StackBlitz (or other editor), we will be able to help you address specific issues.
<div class="hidden">
<input type="text" formControlName="id" placeholder="id" name="id" class="form-control" readonly="true">
</div>
<div class="form-group">
<label for="name">User Name:</label>
<input type="text" formControlName="name" placeholder="name" name="name" class="form-control" id="name" readonly="true" [ngModel]="editForm.name">
</div>
I recommend this documentation for more information
Upvotes: 0