簡體   English   中英

如何在 angular 的表單輸入字段中綁定來自 api 響應的數據

[英]how to bind data from api response in form input feild in 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>

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

您可以在獲取數據后立即制作表單並使用 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>

這是供您參考的工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM