将文本输入绑定到可观察对象中的属性-Angular 2+

何塞软管

我正在使用Angular 5构建应用程序,并且正在尝试构建动态表单。这种形式就像一个赌注单或购物车,是一系列来自可观察服务的对象。我很难弄清楚如何添加输入字段并将其绑定到每个投注对象中的属性。

可观察的betSlipItems数组如下所示:

[
  {
    "Id": 1,
    "betslipTeamName": "La Rochelle",
    "stake": null
  },
  {
    "Id": 2,
    "betslipTeamName": "North Queensland Cowboys",
    "stake": null
  }
] 

我想做的是创建一个输入字段,并将其绑定到每个投注对象的“赌注”属性。

到目前为止,这是我对bet-slip.component.ts的代码

import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { Component, OnInit, Input } from '@angular/core';
import { Bets } from '../../../shared/models';
import { BetService } from '../../../shared/services/bet.service';
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';

@Component({
  selector: 'bet-slip',
  templateUrl: './bet-slip.component.html',
  styleUrls: ['./bet-slip.component.scss']
})

export class BetSlipComponent implements OnInit {

  public betSlipItems$: Observable<Bets[]> = of([]);
  public betSlipItems: Bets[] = [];
  public betsForm: FormGroup;

  constructor( private betService: BetService, private _fb: FormBuilder) {
    this.betSlipItems$ = this.betService.getBets();
  }

  ngOnInit() {

    this.betsForm = new FormGroup({
        stake: new FormControl()
    });

    this.betSlipItems$.subscribe((betSlipItems) => {
      this.betSlipItems = betSlipItems;
    });

  }
}

我的组件bet-slip.component.html看起来像这样:

 <form [formGroup]="betsForm">
      <div *ngFor="let bet of betSlipItems; let i=index">
        {{bet.betslipTeamName }}
        <input type="text" formControlName="stake">
      </div>
 </form>

我知道这是不正确的。我怎样才能解决这个问题?

埃利索

问题是您必须知道什么需要和期望什么。我想您想制作一个不仅带有“ Id”,“ betslipTeamName”和“ stake”(至少需要Id和股份)的表单数组。使用带有数组的ReactiveForm很容易。通常,我们有一个返回数据的服务。我举了一个完整的例子,希望对您有帮助

//simple service that read a json (you have one yet -it's only to complete my example-)
@Injectable()
export class AppDataService {

  constructor(private httpClient:HttpClient) { }
  read(key:any)
  {
    return this.httpClient.get('../assets/data.json')
  }
}

我们的组件有一个.html这样的

<div *ngIf="yet">
<!--I put a *ngIf to avoid an error at first-->
  <form [formGroup]="dataForm" (ngSubmit)="submit(dataForm)" novalidate>
    <!--see that the "formArrayName" is "lista" 
    don't confuse with the *ngFor of "lista" (the lista in ngFor is a getter)
    -->
    <div formArrayName="lista" *ngFor="let lista of lista.controls;let i=index">
      <div [formGroupName]="i"> <!--it's necesary a formGroupName=i-->
      <!--we can use labels here -->
      {{labels[i].Id}}{{labels[i].Text}}
          <!--the input we need , some can be readOnly -->

          <input type="text" class="form-control" formControlName="Id">
          <input type="text" class="form-control" formControlName="betslipTeamName">
          <input type="text" class="form-control" formControlName="stake">
      </div>
      <hr>
    </div>
  </form>
   <!---this it's only to check the value of the form-->
  {{dataForm?.value |json}}
</div>

像component.ts

@Component({
  selector: 'app-app-form',
  templateUrl: './app-form.component.html',
  styleUrls: ['./app-form.component.css']
})
export class AppFormComponent implements OnInit {

  dataForm: null | undefined | FormGroup;  //we have a dataForm
  data: any;  //normally we have a data too. It's not necesary that the data was identical to dataFrom 
  labels:any[] //we create an array [{Id,Text}]
  yet:boolean=false;  //I use this variable when all it's ready

  get lista() {  //<--This is the gettet that we use in the *ngFor
    return (this.dataForm) ? this.dataForm.get('lista') : null;
  };

  constructor(private fb: FormBuilder, private dataService: AppDataService) { }

  ngOnInit() {
    let key: any;
    this.dataService.read(key).subscribe(
      (response:any[]) => {
    if (response) {
      this.data = response; //this.data is an array[{"Id": 1,..}.{"Id":2..}]
      //You can create a label array with Id,Text
      this.labels=response.map((item:any)=>{return {Id:item.Id,Text:item.betslipTeamName}})
      this.dataForm = this.createFormGroup(this.data);// dataForms is an object {lista:[{..},{..}]}
      this.yet=true;
    }
  });
  }
  submit(dataForm:any)
  {
    if (dataForm.valid)
    {
      console.log(dataForm.value);
    }
  }
  createFormGroup(data: any) {
    let lista = this.buildArray(data);  //create an array of Controls

    let dataForm = this.fb.group({
      lista: lista
    });
    //see that dataForms is an object {lista:[{..},{..}]}
    return dataForm;
  }

  buildArray(myArray: any[]) {
    //witch each data, we create a fbGroup 
    const arr = myArray.map(data => {
      return this.fb.group({
        "Id": [data.Id], //we can omit some control
        "betslipTeamName": [data.betslipTeamName],
        "stake": [data.stake],
      });
    });
    //And return a array of fbGroup
    return this.fb.array(arr);
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Angular 2中为模拟数据创建可观察对象

在Angular 2中对可观察对象进行单元测试

将类型为datetime-local的输入绑定到Angular 2中的Date属性

Angular 2无法在可观察到的回调中访问它

如何在Angular2的可观察对象中创建可观察对象

Angular 2形式:将html select绑定到对象集合

Angular2:守卫中的嵌套可观察对象

在Angular2中可观察到的组件属性变化

在组件之间共享可观察对象/在Angular2中多播可观察对象

每次在Angular 2中满足条件时,rxJS即可观察到重复调用

Rxjs结合了2个可观察对象,Angular 2

模拟服务调用返回Angular 2中的可观察对象?

Angular2可观察到的问题,无法读取未定义的属性“订阅”

使用Angular2将动态对象绑定到HTML

Angular2 / Typescript对象和属性绑定到模板

Angular2:子属性更改时更新可观察对象(嵌套的可观察对象)

Angular 2中的身份验证,处理可观察对象

在Angular 2中链接RxJs可观察对象

Angular2-将ngModel绑定到属性的引用

在Angular 2中观察对象属性的变化

Angular 2将所选属性绑定到动态创建的选项

Angular2-返回在map函数中创建的对象的可观察对象

Angular 2:如何将子组件绑定到属性

Angular2中的输入属性绑定

angular2将事件绑定到可观察对象

Angular2中的可观察对象

Angular2:将可观察数组绑定到组件时出错

如何将对象属性绑定到 angular2 中的文本框

Angular 2:将响应值绑定到循环 ngFor 中的输入类型