Angular 2 - 无法设置表单数组值

Angular 2 - Can't set form array value

我收到这个错误:

There are no form controls registered with this array yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout).

使用此代码时:

public settingsForm: FormGroup = this.fb.group({
  collaborators: this.fb.array([]),
  rsvp: this.fb.group({
    latestDate: ['', [Validators.required]],
    latestTime: ['', [Validators.required]],
    guestLimit: ['', [Validators.required]],
    isRSVPOpen: false,
    isGuestPlusOne: false,
    isAutoApproveToGuestlist: false,
    isOnlyFacebookRSVP: false,
    isBirthdayAndPhoneRequired: false
  }),
  tickets: this.fb.group({
    info: this.fb.group({
      closingDate: '',
      closingTime: ''
    }),
    types: this.fb.array([])
  })
});

里面 ngOnInit:

this.eventSubscription = this.af.database.object('/events/' + this.eventId)
  .filter(event => event['$value'] !== null)
  .subscribe((event: IEvent) => {

    const settings: ISettings = event.settings;
    const collaborators: ICollaborator[] = settings.collaborators;
    const rsvp: IRSVP = settings.rsvp;
    const tickets: ITickets = settings.tickets;

    this.settingsForm.setValue({
      collaborators: collaborators || [],
      rsvp: rsvp,
      tickets: {
        info: tickets.info,
        types: tickets.types || []
      }
    });
  }
);

collaborators 包含一个值时,即它不是 undefinednull 或空 [],类似于:

[
  {
    email: 'foo@bar.com',
    role: 1
  },
  {
    email: 'baz@bar.com',
    role: 2
  }
]

然后应用程序在 eventSubscription 中的 setValue 行崩溃。

我不明白为什么会这样。

有什么想法吗?

您必须在设置其值之前构建表单 OnInit。尝试这样的事情:

settingsForm: FormGroup; 

buildForm(): void {
   settingsForm: FormGroup = this.fb.group({
      //content of settingsForm
   })
}

ngOnInit() {
    this.buildForm();
    this.eventSubscription = this.af.database.object('/events/' + this.eventId)
    //...
    this.settingsForm.setValue({ //you can try .patchValue to set only available value
        //...
    })
}

用控件初始化表单数组。那将解决问题。如果您需要了解如何操作,请参阅 Reactive Forms 指南。如果您正在使用 ngModel,可能值得将其删除。

我认为这段代码会有所帮助

 import { FormArray, FormBuilder, FormGroup} from '@angular/forms';

export class SomeComponent implements OnInit {

consutructor(public  fb:FormBuilder) { }

    public buildcollaboratorsGroup(fb:FormBuilder):FormGroup {
        return fb.group({
                            email:'',
                            role:''
                });
    }

ngOnInit() {
    public settingsForm: FormGroup = this.fb.group({
    collaborators:this.fb.array([this.buildcollaboratorsGroup(this.fb)])
    });     

    this.setFormArrayValue();
 }


    // I am trying set only one value if it's multiple use foreach        
    public setFormArrayValue() {
        const controlArray = <FormArray> this.settingsForm.get('collaborators');
        controlArray.controls[0].get('email').setValue('yourEmailId@gmail.com');
        controlArray.controls[0].get('role').setValue(2);
    }

    // I am trying remove only one value if it's multiple use foreach        
    public removeFormArrayValue() {
        const controlArray = <FormArray> this.settingsForm.get('collaborators');
           controlArray.removeAt(0);        
    }
}

在 FormGroup 或 FormArray 上调用 setValue(data) 之前,FormGroup 或 FormArray 必须具有与 data完全 相同的结构。只有结构很重要,FormGroup 或 FormArray 中的值将被替换为 data.

例如,如果您的数据是

let data = [ {a: 1, b:2}, {a: 3, b: 4} ]

那么FormArray必须有2个FormGroup,每个FormGroup必须有一个FieldControl叫a和一个叫b。你可以这样做:

let fa = this.formBuilder.array([
  this.formBuilder.group({a: 0, b:0}),
  this.formBuilder.group({a: 0, b:0})
])
fa.setValue(data)

如果您的数据具有更复杂的结构,则 FormArray 需要具有相同的复杂结构。