私は選択の数に応じて異なる行数の折れ線グラフを表示するアプリケーションを持っています(選択された各フィールドにつき1行、最大5つの選択)。最初の2つはあらかじめ定義されているのでうまく動作しますが、私は(変更)= "関数"を指定できます。他の3つはオプションなので、htmlにselectを追加するボタンを追加しました。唯一の問題は、それらを動的に追加すると、グラフィックを再描画するはずのonchange関数を想定していないことです。角2はonchangeでhtml要素を作成します
は、ここに私のコードのサンプルです:
add() {
var child = document.getElementById('addField');
var selectList = document.createElement("select");
if (child.previousElementSibling) {
selectList.id = "field" + (parseInt(child.previousElementSibling.id.charAt(child.previousElementSibling.id.length-1)) + 1);
selectList.innerHTML = selectList.innerHTML + child.previousElementSibling.innerHTML;
}
else {
selectList.id = "field" + (parseInt(child.previousElementSibling.id.charAt(child.previousElementSibling.id.length-1)) + 1);
selectList.innerHTML = selectList.innerHTML + child.previousElementSibling.innerHTML;
}
if(parseInt(selectList.id.charAt(selectList.id.length-1)) > 5)
alert("Maximum number of parameters is : 5");
else {
selectList.setAttribute('onchange', "drawChart()");
child.parentNode.insertBefore(selectList, child);
}
}
この機能はなaddFieldボタンの上の選択を追加することであり、それはdrawChartが存在しないことを言います。
<div id="principal">
<label>Parameters :</label>
<select id="field1" (change)="drawChart()">
<option *ngFor="let pos of array"
[value] = "pos.name"
[selected]="pos.name == 'def'">
{{pos.name}}
</option>
</select>
<select id="field2" (change)="drawChart()">
<option *ngFor="let pos of array"
[value] = "pos.name"
[selected]="pos.name == 'def2'">
{{pos.name}}
</option>
</select>
<input type="button" class="button" id="addField" value="Add Field" (click)="add()"/>
</div>
なぜDOMに直接書き込んでいますか?テンプレートを使用します。 同じコンテキストで作業していないため、onchangeがwindow.drawChart()関数を待機しているため、「drawChart()」が機能しません。 –
それはこれを行う角度の方法ではありません。テンプレートでも動的要素を定義し、インスタンスに* ngIf = "showOptional"などの条件を追加する必要があります。 – cy3er
コンポーネントで動的要素を定義するにはどうすればよいですか? @ cy3er –