gpt4 book ai didi

javascript - 错误类型错误 : Cannot read property 'invalid' of undefined while trying to list FormArray of FormGroups in Angular

转载 作者:行者123 更新时间:2023-12-02 21:25:01 24 4
gpt4 key购买 nike

我有一个可以根据客户需求进行修改的项目。为了获取具有不同修改的项目列表,我决定创建一个表单,他们可以在其中添加所需数量的项目并为每个项目选择规范。为此,我需要创建一个 FormGroups 的 FormArray。一切都按照它必须的方式进行编译,但是当程序尝试呈现表单时出现错误:错误类型错误:无法读取未定义的属性“无效”

这是我的 app.component.ts 的代码(items 和 addItem())

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
form: FormGroup

ngOnInit() {
this.form = new FormGroup({
companyName: new FormControl('', Validators.required),
items: new FormArray([])
})
this.addItem()
}

submit() {
if(this.form.valid){
console.log('Form submited', this.form)
const formData = {...this.form.value}

console.log('Form Data: ', formData)
}
}

controlSelectChanged() {
if(this.form.get('item').get('controlSelect').value == 'Ручное'){

}
}

addItem() {
const item = new FormGroup({
modelSelect: new FormControl('', Validators.required),
quantity: new FormControl('', Validators.required),
width: new FormControl('', Validators.required),
height: new FormControl('', Validators.required),
colorSelect: new FormControl('', Validators.required),
factorySelect: new FormControl('', Validators.required),
articleSelect: new FormControl('', Validators.required),
articleSelect2: new FormControl('', Validators.required),
controlSelect: new FormControl('', Validators.required),
controlSideSelect: new FormControl('', Validators.required),
controlFactorySelect: new FormControl('', Validators.required),
controlAcceptorSelect: new FormControl('', Validators.required),
automaticFactorySelect: new FormControl('', Validators.required),
quantityPult: new FormControl('', Validators.required),
automaticAdditionSelect: new FormControl('', Validators.required),
notes: new FormControl(''),
});
(this.form.get('items') as FormArray).push(item)
console.log(this.form.get('items'))
}
}

这是从 app.component.html 渲染此数组的代码片段

<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group invis">
<label for="inputCompanyName">Название вашей компании</label>
<input type="email" class="form-control" id="inputCompanyName" formControlName="companyName" aria-describedby="companyNameHelp" placeholder="Введите название компании">
<small id="companyNameHelp" class="form-text text-muted">Это поле обязательно для заполнения.</small>
<button type="button" class="btn btn-primary mt-20" [disabled]="form.controls['companyName'].invalid">Далее</button>
</div>

<div *ngFor="let item of form.get('items')" class="form-group">
<ng-container [formGroupName]="item">
<div class="form-row">
<div class="form-group col">
<label for="modelSelect">Модель</label>
<select class="form-control" id="modelSelect" formControlName="modelSelect">
<option>ASN130</option>
<option>ASN</option>
<option>ASN110 cab</option>
<option>ASN 110 GPZ TENS</option>
<option>Зашивка на люверсах</option>
</select>
</div>

<div class="col-md-1">
<label for="quantity">Кол-во</label>
<input type="text" class="form-control" id="quantity" placeholder="-" formControlName="quantity">
</div>

<div class="col-md-1">
<label for="width">Ширина</label>
<input type="text" class="form-control" id="width" placeholder="-" formControlName="width">
</div>

<div class="col-md-1">
<label for="height">Высота</label>
<input type="text" class="form-control" id="height" placeholder="-" formControlName="height">
</div>

<div class="form-group col">
<label for="colorSelect">Цвет профилей</label>
<select class="form-control" id="colorSelect" formControlName="colorSelect">
<option>9003 Белый</option>
<option>9004 Черный</option>
<option>8017 Коричневый</option>
<option>7024 Антрацит</option>
<option>1024 Бежевый</option>
</select>
</div>

<div class="form-group col">
<label for="factorySelect">Производитель тента</label>
<select class="form-control" id="factorySelect" formControlName="factorySelect">
<option>COPACO</option>
<option>DICKSON</option>
<option>М8</option>
</select>
</div>

<div class="form-group col">
<label for="articleSelect">Артикул тента</label>
<select class="form-control" id="articleSelect" formControlName="articleSelect">
<option>COPACO</option>
<option>DICKSON</option>
<option>М8</option>
</select>
</div>

<div class="form-group col">
<label for="articleSelect2">Сторона</label>
<select class="form-control" id="articleSelect2" formControlName="articleSelect2">
<option>Back со стороны короба</option>
<option>Front со стороны короба</option>
<option>Back со стороны подворота</option>
<option>Front со стороны подворота</option>
</select>
</div>

</div>
<div class="form-row">
<div class="form-group col">
<label for="controlSelect">Управление</label>
<select class="form-control" id="controlSelect" formControlName="controlSelect" (change)="controlSelectChanged()">
<option>Ручное</option>
<option>Автоматическое</option>
</select>
</div>

<div class="form-group col">
<label for="controlSideSelect">Сторона управления </label>
<select class="form-control" id="controlSideSelect" formControlName="controlSideSelect">
<option>Справа</option>
<option>Слева</option>
</select>
</div>

<div class="form-group col">
<label for="controlFactorySelect">Производитель привода</label>
<select class="form-control" id="controlFactorySelect" formControlName="controlFactorySelect">
<option>Дорхан</option>
<option>Somfy</option>
</select>
</div>

<div class="form-group col">
<label for="controlAcceptorSelect">Вид привода</label>
<select class="form-control" id="controlAcceptorSelect" formControlName="controlAcceptorSelect">
<option>Без приемника</option>
<option>Cо встроенным приемником </option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<label for="automaticFactorySelect">Производитель автоматики</label>
<select class="form-control" id="automaticFactorySelect" formControlName="automaticFactorySelect">
<option>Дорхан</option>
<option>Somfy</option>
</select>
</div>

<div class="col-lg-2">
<label for="quantityPult">Кол-во пультов</label>
<input type="text" class="form-control" id="quantityPult" placeholder="-" formControlName="quantityPult">
</div>

<div class="form-group col">
<label for="automaticAdditionSelect">Дополнительная автоматика</label>
<select class="form-control" id="automaticAdditionSelect" formControlName="automaticAdditionSelect">
<option>Нет</option>
<option>Датчик ветра</option>
</select>
</div>

<div class="col">
<label for="notes">Примечания</label>
<textarea class="form-control" id="notes" rows="3" formControlName="notes"></textarea>
</div>
</div>
</ng-container>
</div>
<div class="form-row justify-content-md-center">
<button type="button" class="btn btn-primary mt-30 addNewItemButton" (click)="addItem()">Добавить новый товар</button>
</div>
<button type="button" class="btn btn-primary mt-20" [disabled]="form.controls['item'].invalid">Далее</button>


<button type="submit" class="btn btn-primary mt-20" [disabled]="form.invalid">submit</button>
</form>

提前致谢!

最佳答案

您可以在这里找到一个工作示例:

https://stackblitz.com/edit/angular-obnxyi

  1. 我使用 formBuilder 来反射组件拥有更清晰的代码。
  2. *NgFor访问 FormArray 控件的正确方法正在使用 form.get('items').controlscontrols使您可以访问控件数组
  3. 我将循环移至 ng-container为了设置 formArrayName重复标记的父级内的属性。所以你现在有 <div formArrayName="items" class="form-group">

关于javascript - 错误类型错误 : Cannot read property 'invalid' of undefined while trying to list FormArray of FormGroups in Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60761661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com