動的フォームを作成しようとしています(リストに無制限にアイテムを追加することができます)が、リストの内容が何も表示されません。パスとコントロール:角2のフォーム "パスでコントロールを見つけることができません"
はパスとコントロールを見つけることができません: 'list_items - > list_item'
マイコンポーネント:
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
listForm: FormGroup;
constructor(private nodeService: NodeService, private messageService: MessageService, private fb: FormBuilder,
private listService: ListService) {
this.listForm = this.fb.group({
title: ['', [Validators.required, Validators.minLength(5)]],
list_items: this.fb.array([
this.initListItem(),
])
});
}
initListItem() {
return this.fb.group({
list_item: ['']
});
}
initListItemType() {
return this.fb.group({
list_item_type: ['']
});
}
addListItem() {
const control = <FormArray>this.listForm.controls['list_items'];
control.push(this.initListItem());
}
テンプレート(list.component.html):
<h2>Add List </h2>
<form [formGroup]="listForm" novalidate (ngSubmit)="addList(listForm)">
<div class="form-group">
<input type="text" class="form-control" formControlName="title" placeholder="Title">
</div>
<div formArrayName="list_items">
<div *ngFor="let list_item of listForm.controls.list_items.controls; let i=index" class="panel panel-default">
{{i + 1}}.) <input type="text" formControlName="list_item" placeholder="List Item" class="form-control">
</div>
<a (click)="addListItem()">Add List Item +</a>
</div>
<button type="submit">Submit</button>
</form>
タイトルはうまくいきますが、エラーの原因となっている「formControlName」でエラーが見つかりません。
この問題のお手伝いをお寄せいただきありがとうございます。
listForm: FormGroup;
constructor(private nodeService: NodeService, private messageService: MessageService, private fb: FormBuilder,
private listService: ListService) {
this.listForm = this.fb.group({
title: ['', [Validators.required, Validators.minLength(5)]],
list_items: this.fb.array([
[''],
])
});
}
addListItem() {
const control = <FormArray>this.listForm.controls['list_items'];
control.push(this.fb.control(['']));
console.log(control)
}
へ
は、これは私が達成しようとするものと干渉しに行くのではありませんか?私は'list_item 'を返す私の'initListItem()'を持っているので、新しいフォームを動的に追加することができます。あなたはこれを達成する方法について別の提案をしていますか? – dowu
ありがとうございました。あなたは私を正しい方向に導いてくれました。私はメインの投稿で変更したものを投稿します:) – dowu
@dowuそれは実際に素晴らしいだろう:) – user776686