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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42786445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:20:48  来源:igfitidea点击:

Angular 2 - Can't set form array value

angulartypescriptangular2-formsangular2-formbuilderreactive-forms

提问by Chrillewoodz

I get this error:

我收到此错误:

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).

还没有使用此数组注册的表单控件。如果您正在使用 ngModel,您可能需要检查下一个刻度(例如使用 setTimeout)。

When using this code:

使用此代码时:

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([])
  })
});

Inside ngOnInit:

内部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 ||?[]
      }
    });
  }
);

When collaboratorscontains a value, i.e it's not undefined, nullor empty [], something like:

collaborators包含一个值时,即它不是undefinednull或为空[],例如:

[
  {
    email: '[email protected]',
    role: 1
  },
  {
    email: '[email protected]',
    role: 2
  }
]

Then the app crashes on the setValueline in the eventSubscription.

然后应用程序崩溃,就setValue在该行eventSubscription

I cannot figure out why this is happening.

我无法弄清楚为什么会发生这种情况。

Any ideas?

有任何想法吗?

采纳答案by Roman C

Initialize the form array with the control. That would resolve the issue. See Reactive Formsguide if you need to know how to do that. If you are using ngModelit would probably worth to remove it.

使用控件初始化表单数组。这样问题就解决了。如果您需要知道如何做到这一点,请参阅Reactive Forms指南。如果您正在使用ngModel它可能值得将其删除。

回答by Jingshao Chen

Before calling setValue(data)on a FormGroup or FormArray, the FormGroup or FormArray must have the exactlysame structure of the data. Only the structure matters, the value in the FormGroup or FormArray will be replaced by data.

拨打电话之前setValue(data)在FormGroup或FormArray的FormGroup或FormArray必须具有完全相同的结构相同data。只有结构很重要,FormGroup 或 FormArray 中的值将被替换为data

Example, if your data is

例如,如果您的数据是

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

Then the FormArray must has 2 FormGroups and each FormGroup must has one FieldControl called aand one called b. You can do something like this:

那么 FormArray 必须有 2 个 FormGroups,每个 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)

If your data is of more complex structure, the FormArray needs to have the same complex structure.

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

回答by mickdev

You have to build your form OnInit before setting its value. Try something like this :

您必须在设置其值之前构建您的表单 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
        //...
    })
}

回答by Praveen M P

I think this code will help

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

 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('[email protected]');
        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);        
    }
}