繁体   English   中英

如何在 Angular 的动态 FormArray 中使用 patchValue?

[英]How to use patchValue inside dynamic FormArray in Angular?

在第一种情况下(工作演示链接) patchValue() 能够操纵 select 下拉菜单,其中反应性 FormGroup() 仅包含 FormControl() ,在第二种情况下,我必须使用与用户添加输入时相同的功能其值显示直接在选择下拉列表中选择; 但是这次我必须在 FormArray() 中使用 patchValue() 设置值,这没有按预期工作。 如何使它在 FormArray() 中工作?

第一种情况

app.component.ts

export class AppComponent {

      entityInfoForm: FormGroup;
    
      items = ['Mobile', 'Home', 'School'];
      
      constructor() {
        this.entityInfoForm = new FormGroup({
           name: new FormControl(""),
           control: new FormControl("")
        });
      }
    
      addCustom(v: string) {
        this.items.push(v);
        this.entityInfoForm.patchValue({control: this.items[this.items.length - 1]});
      }

      onSubmit() {
         console.log(this.entityInfoForm);
      }

   }

app.component.html

<form role="form" [formGroup]="entityInfoForm" (ngSubmit)="onSubmit()">

   <div class="form-group">
       <label for="usr">Name</label>
       <input type="text" class="form-control" id="name" formControlName="name" >
   </div>
 
    <div class="form-group">
       <select formControlName="control">
         <option *ngFor="let item of items" [ngValue]="item">{{item}}</option>
       </select>
   </div>

   <button type="submit">Submit Form</button>

</form>

<input type="text" #custom>
<button (click)="addCustom(custom.value)" >Add</button>

SECOND CASE注意:这里我们使用Dynamic FormArray,这种情况下可以做多个

app.component.ts

export class AppComponent {

  entityInfoForm: FormGroup;

  items = ['Mobile', 'Home', 'School'];

  constructor() {
    this.entityInfoForm = new FormGroup({
       name: new FormControl(""),
       contact: new FormArray([
           new FormGroup({
                type: new FormControl(''),
                contact: new FormControl('')
           })
       ])
    });
  }

  addCustom(v: string) {
    this.items.push(v);
    this.entityInfoForm.patchValue({type: this.items[this.items.length - 1]});
  }

  onSubmit() {
     console.log(this.entityInfoForm);
  }
}

app.component.html

姓名
 <div> <select class="form-control formControlName="type"> <option *ngFor="let item of items" [ngValue]="item">{{item}}</option> </select> </div> </div> </form> <input type="text" #custom> <button (click)="addCustom(custom.value)" >Add</button>

要修补特定元素的值,您应该首先使用.get方法获取特定的 formArray 元素。 然后将值推入数组。

this.entityInfoForm
  .get(['contact', 0])
  // .get('contact.0') // <-- alternative
  ?.patchValue({ type: this.items[this.items.length - 1] });

工作堆栈闪电战

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM