2016-11-18 61 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。永远不要使用像:getElementById,cloneNode,innerHTML,appendChild,removeChild

我的建议是,你仔细看看教程和做饭angular.io提供的书,因为我很抱歉,你的代码的当前状态,你所要求的完全重写

相关问题