Angular开发报错:类型'FormGroup'不存在属性'array'
Hey there! Let's break down what's going wrong here and fix that error quickly.
The Root Cause
You're trying to call .array() on this.subjectDesigneForm—but at that point, subjectDesigneForm hasn't been initialized yet, and even if it was, FormGroup doesn't have an array() method. The array() method belongs to the FormBuilder service you've imported, which is what you should use to create your FormArray.
The Correct Approach
Instead of referencing this.subjectDesigneForm.array(), use this.formBuilder.array() to create the items FormArray when building your parent FormGroup. Here's how to adjust your code:
Step 1: Update the ngOnInit Method
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms'; // Inside your component class subjectDesigneForm!: FormGroup; constructor(private formBuilder: FormBuilder) {} ngOnInit() { // Use formBuilder.array() to create the FormArray for items this.subjectDesigneForm = this.formBuilder.group({ items: this.formBuilder.array([this.createItem()]) // ✅ Correct implementation }); } // Ensure your createItem() returns a FormGroup (example implementation) private createItem(): FormGroup { return this.formBuilder.group({ // Add your form controls here, e.g.: title: ['', Validators.required], content: [''] }); }
Bonus: Accessing the FormArray Later
If you need to add/remove items from the items FormArray elsewhere in your component, create a getter for easier access:
get items(): FormArray { return this.subjectDesigneForm.get('items') as FormArray; } // Use the getter to add new items addNewItem() { this.items.push(this.createItem()); }
That should resolve the "Property 'array' does not exist on type 'FormGroup'" error immediately. The key was using the FormBuilder's built-in array() method instead of trying to call it on an uninitialized (and incompatible) FormGroup instance.
内容的提问来源于stack exchange,提问作者Adeel

