如何在角度输入表单中绑定来自api响应的数据

时间:2019-12-19 12:10:50

标签: angular

我想将我从api获取的数据绑定到反应形式的输入字段。 这是我的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)
})
}

以下是我的html代码。我想将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>

3 个答案:

答案 0 :(得分:0)

使用 patchValue()设置反应形式的值。

尝试这样:

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
})

答案 1 :(得分:0)

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)
})

答案 2 :(得分:0)

您可以在获取数据后立即制作表单,并使用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)
    );
  }
}

然后,您将在模板中使用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>

  

这是您推荐的Working Demo