【问题标题】:FormArray - How to pass a string array to it?FormArray - 如何将字符串数组传递给它?
【发布时间】:2019-04-07 04:56:20
【问题描述】:

这是我的表单组:

this.productGroup = this.fb.group({
  name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
  variants: this.fb.array([
    this.fb.group({
      type: '',
      options: this.fb.array([])
    })
  ])
});

如何将字符串数组传递给options?喜欢这个[ 'string1', 'string2' ]。我在这里获得了这些值:stackblitz,但是我不确定如何填充数组。我想将一个通用字符串数组直接传递给options

variants 数组示例:

variants: [ 
   { type: 'Color', options: ['Red', 'Blue'] },
   { type: 'Size', options: ['Small', 'Medium', 'Big'] }
]

HTML:

<form [formGroup]="productGroup">
  <input formControlName="name">
  <div formArrayName="variants" *ngFor="let item of productGroup.controls['variants'].controls; let i = index;">
    <div [formGroupName]="i">
      <mat-form-field>
        <input type="text" placeholder="Variable Type" aria-label="Number" matInput formControlName="type" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let type of types" [value]="type">
            {{type}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
      <mat-form-field>
        <mat-chip-list #chipList>
          <mat-chip *ngFor="let opt of typesOptionsArray[i]" [selectable]="true"
                    [removable]="true" (removed)="removeOpt(opt, i)">
            {{opt}}
            <mat-icon matChipRemove>cancel</mat-icon>
          </mat-chip>
          <input placeholder="Type Options"
                  [matChipInputFor]="chipList"
                  [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
                  [matChipInputAddOnBlur]="true"
                  (matChipInputTokenEnd)="addOpt($event, i)">
        </mat-chip-list>
      </mat-form-field>
    </div>
    <div class="row">
      <a href="javascript:" (click)="addItem()"> Add Variant </a>
      <a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remove Variant </a>
    </div>
  </div>
</form>

【问题讨论】:

  • 选项值是 UI 中的复选框?
  • 不,是Angular Material MatChips。每次用户添加新芯片(事件)时,我都会得到一个新值,然后将其添加到组件中的字符串数组中。
  • @AjayOjha 我正在尝试 this.typesOptionsArray[index].forEach(type =&gt; { this.productGroup.controls['variants']['options'].push(new FormControl(type)); }); 将字符串数组直接传递给 FormArray
  • 你能分享你的变种html代码吗?
  • @AjayOjha 你去。由于它是动态生成的,因此有点复杂。

标签: javascript arrays angular typescript angular-material


【解决方案1】:

我在stackblitz for adding array value in the options array 上创建了一个示例应用程序。

我建议不要创建选项字段的 FormArray,而是尝试创建 FormControl。我已经更改了创建FormGroup的代码。

这是formgroup的代码。

 this.productGroup = this.fb.group({
  name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])],
  variants: this.fb.array([
    this.fb.group({
      type: '',
      options: ''
    })
  ])
});

我在组件'addOption'和'removeOption'中添加了两个方法,同时添加选项时你需要将一个字符串推送到选项数组中。

代码如下:

let variants = <FormArray>this.productGroup.controls.variants;
let variantFormGroup = <FormGroup>variants.controls[0];
let optionValue = variantFormGroup.controls.options.value;
if(!optionValue)
    optionValue = [];
optionValue.push(`chip${this.currentIndex}`); // push your actutal string value
variantFormGroup.controls.options.setValue(optionValue);

this.currentIndex++; //don't consider this, this is just for adding new name

这是从选项数组中删除字符串值的代码

 let optionValue = this.productGroup.value.variants[0].options;
    if(optionValue.length > 0){
      //let indexOf = optionValue.indexOf(removeValue); find the index number with your value.
      optionValue.splice(0,1);
      let variants = <FormArray>this.productGroup.controls.variants;
      let variantFormGroup = <FormGroup>variants.controls[0];
      variantFormGroup.controls.options.setValue(optionValue);

    }    

这是在选项数组中添加几个值后的 json 结果:

{ "name": "", "variants": [ { "type": "", "options": [ "chip4", "chip5", "chip6", "chip7", "chip8" ] } ] }

如果您有任何问题,请告诉我。

【讨论】:

  • 谢谢!我使用了类似的方法来保存一组图像,但我不确定是否可以动态应用它。
  • 是否可以将options存储在对象数组而不是数组中:this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], variants: this.fb.array([ this.fb.group({ type: '', options: this.fb.array([ this.fb.group({ option: '', photos: '' ]) }) ]) });
  • 可以,需要我设计吗?
  • 是的...我做错了它总是返回一个数组
猜你喜欢
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 2016-12-08
相关资源
最近更新 更多