あなたはRectiveForms
とngModel
-Formsまたは少し難しい方法で最も単純な方法でそれを行うことができますFormArray
。
あなたがここで見つけることができますReactiveFormsについての詳細:ここでhttps://angular.io/guide/reactive-forms
はngModel
hereと解決のための簡単な例では、実施例である:
ステップ1:タイプのTextFieldのDeclate配列
editAuthors: any[] = [];
手順2:あなたの作者の配列を変換する
ngOnInit() {
this.bookModel.authors.forEach((author, index) => {
this.editAuthors.push({ key: 'author'+index, value: author });
});
}
フォームelemetsの作成に必要な新しいeditAuthors-Arrayを入力します。
ステップ3:アドインボタンの機能ここで
addNewTextField(index: number) {
const newTextField: TextField = {
key: 'textfield' + index,
value: ''
}
this.textfields.push(newTextField);
}
新しいテキストフィールドFOTデフォルト値を設定することができます。
ステップ4:あなたはeditAuthors-配列から値を取得し、あなたのbookModel.authors-配列にこれをプッシュする必要があります。このステップでは、フォーム
を提出してください。
showModel() {
this.editAuthors.forEach((author, index) => {
this.bookModel.authors[index] = author.value;
});
// do something with new model
}
ステップ5:テンプレートeditAuthors
て
<div>
<label>Book Tiitle</label>
<input type="text" name="bookTitle" [(ngModel)]="bookModel.title" />
</div>
<div *ngFor="let author of editAuthors;">
<label>Author</label>
<input type="text" [(ngModel)]="author.value" [name]="author.key" />
</div>
<button (click)="addNewAuthor()">Add new Author</button>
<button type="submit" (click)="showModel()">Submit</button>
反復。 name
-attributeと[(ngModel)]
でinputs
を作成してください。要素を構成するデータをバインドする場合は、author.value
を使用します。 author.key
には、固有のname
属性が追加されます。
全TS-ファイル
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
bookModel = {
id: 1,
title: 'Book 1',
authors: [
'Author 1',
'Author 2',
'Author 3'
]
};
editAuthors: any[] = [];
ngOnInit() {
this.bookModel.authors.forEach((author, index) => {
this.editAuthors.push({ key: 'author'+index, value: author });
});
}
addNewAuthor() {
this.editAuthors.push({ key: 'author'+this.editAuthors.length+1, value: '' });
}
showModel() {
this.editAuthors.forEach((author, index) => {
this.bookModel.authors[index] = author.value;
});
console.log(this.bookModel);
}
}
はい、方法があります。最も単純なのは、FormArray:https:// angularを使用することです。io/guide/reactive-forms#form-array-of-formgroupsを使用する-formar-array-present –
私は単純な例でanserを追加しますが、Reactive Formsを使用した例を知りたい場合は、あなたのための例。 –