角4嵌套的下拉列表(Angular 4 nested dropdown)

2019-10-31 04:46发布

我尝试添加一个嵌套的下拉。 如果我们点击“添加城市”,它会创建另一个下拉。 我成功了没有下拉。 请参见下文

..component.html

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <select  formControlName="cities">
    <option *ngFor="let city of myCities; let i=index" [value]='itemname' >
      {{ city }}
    </option>
  </select>
  <br>
  <button>Submit</button>
  <button (click)="addCity()">Add City</button>
  <button (click)="remove(i)">Remove</button>
</form>

component.ts

 form = new FormGroup({
    cities: new FormControl([null]),
  });


  myCities = ['Dhaka','Dubai','Munich'];


  get cities(): FormArray { return this.form.get('cities') as FormArray; }

  addCity() { this.form.get('cities').push(new FormControl())}

  remove(index){ this.form.get('cities').removeAt(index) }

示值误差为波纹管:

E:/angular/nestedForm2/src/app/order-form/order-form.component.ts(21,39):房产 '推' 不上键入 'AbstractControl' 存在。

E:/angular/nestedForm2/src/app/order-form/order-form.component.ts(23,42):房产 'RemoveAt移除' 不上键入 'AbstractControl' 存在。

我曾尝试用不同的方式,但仍然没有找到任何解决方案。 能否请你帮忙?

Answer 1:

为了解决你的错误,你需要你投AbstractControl到它的子类FormArray那里pushremoveAt定义。

(this.form.get('cities') as FormArray).push(new FormControl())
(this.form.get('cities') as FormArray).removeAt(index)

你必须这样做,因为打字稿不能确定的确切类型form.get('cities')因为你通过提供字符串访问它。 只有你作为一个开发人员都知道,根据您在表单中的数据的结构,即form.get('cities')将包含FormArray



Answer 2:

我找到了解决办法。

component.html:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div formArrayName="cities">

      <div *ngFor="let city of cities.controls; let i=index">

        <select [formControlName]="i">

            <option *ngFor="let itemname of myCities" [value]='itemname' >
                {{ itemname }}
            </option>

        </select> 

      </div>

    </div>

    <br>

    <button>Submit</button>
  </form>

  <br>

  <button (click)="addCity()">Add City</button>
  <button (click)="remove(i)">Remove City</button>

component.ts:

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

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

  form = new FormGroup({
    cities: new FormArray([
      new FormControl([null]),
    ]),
  });



  myCities = ['Dhaka','Dubai','Munich'];


  get cities(): FormArray { return this.form.get('cities') as FormArray; }

    addCity() { this.cities.push(new FormControl()); }

    remove(index) { (this.form.get('cities') as FormArray).removeAt(index) }

  constructor() { }

  ngOnInit() {
  }

  onSubmit() {
    console.log(this.cities.value);  // ['SF', 'NY']
    console.log(this.form.value);    // { cities: ['SF', 'NY'] }
  }

  setPreset() { this.cities.patchValue(['LA', 'MTV']); }


}


文章来源: Angular 4 nested dropdown
标签: angular