1

我创建了一个 stackblitz 应用程序来在这里演示我的问题:https ://angular-ry1vc1.stackblitz.io/

我在选择 HTML 列表上有 formArray 值。每当用户更改选择时,它应该在页面上显示选择的值。问题是我怎样才能只显示当前选择并且它不应该覆盖之前选择的值。我想知道如何使用key来使值的占位符独一无二。TIA

form.html

<form [formGroup]="heroForm" novalidate class="form">
  <section formArrayName="league" class="col-md-12">
    <h3>Heroes</h3>
    <div class="form-inline" *ngFor="let h of heroForm.controls.league.controls; let i = index" [formGroupName]="i">
      <label>Name</label>
      <select (change)="onSelectingHero($event.target.value)">
        <option *ngFor="let hero of heroes" [value]="hero.id" class="form-control">{{hero.name}}</option>
      </select> <hr />
      <div>
        Hero detail: {{selectedHero.name}}
      </div> <hr />
    </div>
    <button (click)="addMoreHeroes()" class="btn btn-sm btn-primary">Add more heroes</button>
  </section>
</form>

component.ts

import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators, NgForm } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  heroes = [];
  heroForm: FormGroup;
  selectedHero;

  constructor(
    private fb: FormBuilder,
  ) {
    this.heroForm = fb.group({
      league: fb.array([
        this.loadHeroes(),
        this.loadHeroes(),
        this.loadHeroes()
      ])
    });
  }

  ngOnInit() {
    this.listHeroes();
  }

  public addMoreHeroes() {
    const control = this.heroForm.get('league') as FormArray;
    control.push(this.loadHeroes());
  }

  public loadHeroes() {
    return this.fb.group(
      {
        id: this.heroes[0],
        name: '',
        level: '',
        skill: '',
      }
    );
  }  

  public listHeroes() {
    this.heroes = [
      {
        id: 1,
        name: 'Superman'
      },
      {
        id: 2,
        name: 'Batman'
      },
      {
        id: 3,
        name: 'Aquaman'
      },
      {
        id: 4,
        name: 'Wonderwoman'
      }      
    ];
  }

  public onSelectingHero(heroId) {
    this.heroes.forEach((hero) => {
      if(hero.id === +heroId) {
        this.selectedHero = hero;
      }
    });
  }
}
4

1 回答 1

0

如果这样做的目的是仅通过数组元素显示选定的英雄,而不是替换所有选定的值,那么您可以使用数组表单元素获得一些帮助。

A.onSeletingHero andselectedHero不是必须的,我通过 属性替换了使用表单值formControlName,在这个例子中id控件是select. 这h.value.id是获取选定值id的方法。

    <select formControlName="id">
        <option *ngFor="let hero of heroes;" [value]="hero.id" class="form-control">{{hero.name}}</option>
      </select> <hr />
      <div>
        Hero detail: {{getHeroById(h.value.id).name}}
      </div> <hr />
    </div>

B. 为了获得选中的英雄,我添加了一个getHeroById方法。

  getHeroById(id: number) {
    return id ? this.heroes.find(x => x.id === +id) : {id: 0, name: ''};
  }

希望这些信息能解决您的问题。干杯

于 2017-12-23T03:55:56.117 回答