简体   繁体   English

如何在 angular 的表单输入字段中绑定来自 api 响应的数据

[英]how to bind data from api response in form input feild in angular

I want to bind my data which i am getting from api to input field of the reactive form.我想将从 api 获取的数据绑定到反应形式的输入字段。 Here is my ts code这是我的 ts 代码

ngOnInit() {
this.profileForm = this.formBuilder.group({
  name: ['']
});

this.route.paramMap.subscribe(routeParam => {
  const id = parseInt(routeParam.get('id'));
  console.log(id)
  this.zoneId = id
  this.getZoneData();
})
 }        
  getZoneData() {
    this.zone_service.getZoneById(this.zoneId).subscribe((res) => {
    console.log(res)
    this.zoneName = res.name;
  console.log(this.zoneName)
})
}

Below is my html code.下面是我的 html 代码。 I want to bind zoneName to the form input below我想将 zoneName 绑定到下面的表单输入

        <form [formGroup]="profileForm" (ngSubmit)="save(profileForm.value)">
         <div class="form-group row">
          <label for="zname" class="col-sm-2 col-form-label">Zone Name</label>
         <div class="col-sm-10 txt-box">
          <input type="text" name="zname" formControlName="name" id="zoneName"                        
        class="form-control" placeholder="Enter Zone name" >
                    </div> </div>
                <div class="form-group row">
                    <div class=" col-md-10">
                        <button type="submit" class="a-btns btn btn-success">Save</button>
                    </div>
                </div>
            </form>

Use patchValue() to set values of a reactive form.使用patchValue()设置反应形式的值。

Try like this:像这样尝试:

getZoneData() {
  this.zone_service.getZoneById(this.zoneId).subscribe((res) => {
    this.profileForm.patchValue(res); // set value of all properties        
    this.profileForm.controls.name.patchValue(res.name); // set value of single property
})
getZoneData() {
  this.zone_service.getZoneById(this.zoneId).subscribe((res) => {
  console.log(res)
  this.zoneName = res.name;
  this.profileForm.controls.name.setValue(res.name)
  console.log(this.zoneName)
})

You could make the form right after getting the data and initialize the form's properties with the res values, something like this:您可以在获取数据后立即制作表单并使用 res 值初始化表单的属性,如下所示:

import { Component } from "@angular/core";
import { FormGroup, FormBuilder } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs";
import { switchMap, tap, map } from "rxjs/operators";
import { ZoneService } from "./zone.service";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  profileForm$: Observable<FormGroup>;
  zoneId;
  zoneName;

  constructor(
    private route: ActivatedRoute,
    private formBuilder: FormBuilder,
    private zone_service: ZoneService
  ) {}

  ngOnInit() {
    this.profileForm$ = this.route.paramMap.pipe(
      switchMap(routeParam => {
        const id = +routeParam.get("id");
        this.zoneId = id;
        return this.getZoneData();
      }),
      map(name =>
        this.formBuilder.group({
          name: [name]
        })
      )
    );
  }

  getZoneData() {
    return this.zone_service.getZoneById(this.zoneId).pipe(
      tap(res => (this.zoneName = res.name)),
      map(res => res.name)
    );
  }
}

You would then use an async pipe in the template to unwrap the form like this:然后,您将在模板中使用async管道来解开表单,如下所示:

<div *ngIf="profileForm$ | async as profileForm">
  <form 
    [formGroup]="profileForm" 
    (ngSubmit)="save(profileForm.value)">
    <div class="form-group row">
      <label for="zname" class="col-sm-2 col-form-label">Zone Name</label>
      <div class="col-sm-10 txt-box">
        <input 
          type="text" 
          name="zname" 
          formControlName="name" 
          id="zoneName" 
          class="form-control" 
          placeholder="Enter Zone name">
      </div>
    </div>
    <div class="form-group row">
      <div class=" col-md-10">
        <button type="submit" class="a-btns btn btn-success">Save</button>
      </div>
    </div>
  </form>
</div>

Here's a Working Demo for your ref.这是供您参考的工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM