2016-11-18 5 views
0

+ボタンをクリックすると新しい行を複製する必要があります。その新しい行には、-ボタンが含まれています。このボタンは、新しく作成された行を削除します。問題は、その新しい-ボタンにクリックイベントを付けることができることです。以下はAngular2の新しい要素にイベントをアタッチする

は、フォームを含むTSである:

import { Component, OnInit, ViewEncapsulation, ElementRef } from '@angular/core'; 
import { MailSegmentObject } from './mailSegmentObject'; 
import { MailSegmentRule } from './mailSegmentRule'; 

@Component({ 
    selector : 'segment-form', 
    templateUrl : 'app/html/createSegment.html', 
    styleUrls : ['node_modules/bootstrap/dist/css/bootstrap.min.css'], 
    encapsulation : ViewEncapsulation.Native 
}) 

export class CreateSegmentComponent { 

counter : number = 0; 
segment : MailSegmentObject = new MailSegmentObject(); 

addNewRule() : void { 
    var origElem = document.getElementById("mandatoryRule"); 
    var copyElem = <HTMLDivElement>origElem.cloneNode(true); 
    copyElem.setAttribute("id", "mandatoryRule_" + (this.counter++)); 
    copyElem.innerHTML += "<div class=\"col-sm-1\"><button type=\"button\" class=\"btn btn-default\" (click)=\"deleteRule(this)\">-</button></div>"; 
    origElem.parentElement.appendChild(copyElem); 
} 

deleteRule(elem) : void { 
    console.log("asdasdasdasdasd"); 
    elem.parentElement.removeChild(elem); 
} 
} 

とHTMLは次のとおりです。

<div class="container" style="margin-top: 15px;"> 
    <form class="form-horizontal"> 
     <div class="form-group"> 
     <label class="control-label col-sm-2" for="Segment Name">Segment Name</label> 
     <div class="row"> 
      <div class="col-sm-12"> 
       <input type="text" class="form-control" id="segmentNameInput" placeholder="Segment Name"> 
      </div> 
     </div> 
     </div> 
     <div class="form-group"> 
     <label class="control-label col-sm-2" for="pwd">Select Property</label> 
     <div class="row rule" id="mandatoryRule"> 
      <div class="col-sm-3"> 
       <select class="form-control"> 

       </select> 
      </div> 
      <div class="col-sm-3"> 
       <select class="form-control"> 

       </select> 
      </div> 
      <div class="col-sm-3"> 
       <input type="text" class="form-control"> 
      </div> 
     </div> 
     <div class="col-sm-1"> 
      <button type="button" class="btn btn-default" (click)="addNewRule(this)">+</button> 
     </div> 
     </div> 
     <div class="form-group"> 
     <div class="col-sm-offset-2 col-sm-8"> 
      <button type="submit" class="btn btn-default">Submit</button> 
     </div> 
     </div> 
    </form> 
</div> 

は親切に私を助けます。おかげさまで

答えて

1

これは、angular2の概念に完全に書かれています。 linesのコレクションに*ngForを使用する必要があります。いつでも決して - getElementByIdcloneNodeinnerHTMLappendChildremoveChildのようなものを使用しないでください。

私の提案は、私は申し訳ありませんので、あなたのコードの現在の状態で、チュートリアルに詳しく見ていくとangular.ioに設けた本を調理することで、あなたは完全に書き直した

を求めています
関連する問題