#必要な数だけ行を増やしながら入力できるようにする【Angular】
##入力欄を追加する
入力する行数を固定せずに、必要な数だけ行を増やしながら入力できるようにする。
「Getしたデータをhtmlとの間で受け渡す」で書いたようにhtmlのテーブルにts側のデータをひも付ける。ボタンから行追加のメソッドを呼び出す。
component.html
<input type="submit" value="行追加" (click)="AddRow()" />
<table class='table' id="adding_table" *ngIf="makers">
<thead>
<tr>
ts側のメソッドでは、idでテーブルを指定し、行を追加する。その行に対し、テキストボックス、セルというふうに子要素から作成して親要素にアペンドしていく。
値を取得する際は最終的な行数分ループ処理し、エレメントのidに含まれる行インデックスによってどのセルに何の値が入力されたかを取り出すことができる。
component.ts
AddRow() {
var adding_table= <HTMLTableElement>document.getElementById("adding_table");
if (adding_table!= null) {
var rowId = (this.rowCount).toString();
var newRow = edit_table.insertRow(1);
var cellProductName = newRow.insertCell(0)
var textName = document.createElement("input");
textName.setAttribute("type", "text");
textName.setAttribute("class", "yellow_color");
textName.setAttribute("style", "width: 100%");
// idに行インデックスを含めておく。
textName.setAttribute("id", "product_name-" + rowId);
cellName.appendChild(textName);
var cellWithReport = newRow.insertCell(1);
var checkReport = document.createElement("input");
checkReport .setAttribute("type", "checkbox");
checkReport .setAttribute("style", "text-align: left;");
// idに行インデックスを含めておく。
checkReport .setAttribute("id", "with_report-" + rowId);
cellWithReport .appendChild(checkReport );
this.rowCount++;
}