将事件附加到Angular2中的新元素

时间:2016-11-18 07:26:45

标签: javascript angularjs angular

我需要点击+按钮复制一个新行。该新行包含一个-按钮,该按钮将删除该新创建的行。所以问题是我可以将点击事件附加到新的-按钮。

以下是包含以下形式的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 个答案:

答案 0 :(得分:1)

这完全是针对angular2的概念而写的。您应该在*ngFor的集合上使用lines。永远不要使用以下内容:getElementByIdcloneNodeinnerHTMLappendChildremoveChild

我的建议是你仔细查看angular.io提供的教程和烹饪书,因为对不起,对于代码的当前状态,你要求完全重写