【发布时间】:2019-09-13 07:53:22
【问题描述】:
我正在使用 formArray 创建动态表单。但我遇到了 “TypeError:无法读取未定义的属性'控件'”
enter code here
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Trainner Registration Form ';
registrationForm: FormGroup;
get LanguagesForm() {
return this.registrationForm.get('Languages') as FormArray;
}
addLanguage() {
this.LanguagesForm.push(this.fb.control(''));
}
constructor(private fb : FormBuilder ) {}
ngOnInit(){
this.registrationForm = this.fb.group({
personalDetails : this.fb.group({
name: this.fb.group({
firstName: [''],
lastName: ['']
}),
aboutYours: [''],
dob: [''],
// lang: [''],
Languages: this.fb.array([]),
wTT: ['']
})
});
}
onSubmit() {
console.log(this.registrationForm.value);
// this._registerationservice.register(this.registrationForm.value).subscribe(
// response => console.log('Success', response),
// error => console.log('Error',error)
// );
}
}
预期结果:如果用户单击“添加语言”按钮,应创建一个新的输入字段。
实际结果:我收到“TypeError: Cannot read property 'controls' of undefined”
app.component.html 文件
<div style="text-align:center">
<h1>Welcome to {{ title }}!</h1>
</div>
<mat-horizontal-stepper >
<mat-step [stepControl]="personalDetails">
<ng-template matStepLabel>Enter Personal Details</ng-template>
<div formGroupName="personalDetails">
<div formGroupName="name">
<div class="form-group">
<label>First Name : </label>
<input type="text" formControlName="firstName" class="form-control" >
</div>
<div class="form-group">
<label>Last Name : </label>
<input type="text" formControlName="lastName" class="form-control">
</div>
</div>
<div class="form-group">
<label>DOB : </label>
<input type="date" formControlName="dob" class="form-control">
</div>
<div class="form-group">
<label>About Yourself : </label>
<textarea formControlName="aboutYours" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Language(s) : </label>
<button type="button" class="btn btn-secondary btn-sm m-2" (click)="addLanguage()">Add Language</button>
<!-- <input type="text" formControlName="lang" class="form-control"> -->
<div formArrayName="Languages">
<div *ngFor="let lang of langsform.controls; let i =index;">
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>
</div>
</mat-horizontal-stepper>
</form>
</div>
【问题讨论】:
-
你能提供 addLanguage() 函数让我们看看里面是什么吗? @GRV
-
check mu 回答你需要从表单数组中设置上父级????
-
使用 getter 并获取 ts 文件中的控件。您的 IDE 将为您提供帮助,您将知道您的代码是 typescript 安全的
-
@HarisHajdarevic 请检查更新的代码。谢谢
-
@GRV 你检查我的答案了吗??
标签: javascript angular typescript