如何添加click事件以在typescript

时间:2017-03-09 10:25:52

标签: html angular typescript ionic2

我正在以角度2构建应用程序。我想在动态添加的html元素中添加click事件。 我定义了一个字符串(contentString),在这个字符串中我定义了html元素。

var contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + '<br/> Click here for more information <button (click)="navigate()">Navigate here</button>'; 

这个字符串放在一个像这样的html元素中:

var boxText = document.createElement("div");
    boxText.innerHTML = contentString;

虽然当我检查元素时,它已定义了click事件,但它没有触发。

[image 1]

[image 2]

单击它应该是控制台日志

navigate() {
console.log("eeeehnnananaa");
}

但这不起作用。 有人解决方案吗?

3 个答案:

答案 0 :(得分:13)

Angular在编译组件时处理模板。之后添加的HTML不再编译,并且会忽略绑定。

您可以使用

constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  // assume dynamic HTML was added before
  this.elRef.nativeElement.querySelector('button').addEventListener('click', this.onClick.bind(this));
}

答案 1 :(得分:0)

在我的情况下,我这样做-

var boxText = document.createElement("div");
const contentString = '<b>' + this.mName + '</b><br/> ' + this.mObject.category + 
'<br/> Click here for more information ';//as per your code

boxText.innerHTML = contentString;

const button = document.createElement('button');
button.addEventListener('click', (e) => {
    this.navigate();//your typescript function
});
button.innerText = 'Navigate here';
boxText.appendChild(button);

答案 2 :(得分:-1)

Call click event dynamically

ConfirmThisOrder(obj) {
    var orderItemID = obj.target.dataset.oid;
}

ItemDetails(orderId, itemIndex) {
if ($("#accordionNew" + itemIndex).closest("div").html().indexOf("div_" + orderId) == -1) {
  this.oRequest = new ORequestParameter();
  var retrievedObject = localStorage.getItem('userObject');
  let userObject = JSON.parse(retrievedObject) as AdminDashboardModel;
  this.oRequest.SellerId = userObject.sellerId;
  this.oRequest.OrderStatus = $("#hdnOrderStatus").val().toString();
  this.oRequest.OrderId = orderId;
  this.oRequest.OrderConfirmationFlag = '0,1,2';
  let sProviderId = "0";
  if (this.MultiSelectObjTypeSelected != undefined) {
    let result2 = this.MultiSelectObjTypeSelected.map(a => a.id);
    if (result2.join().length > 0) {
      sProviderId = result2.join();
    }
  }
  this.oRequest.ProviderID = sProviderId;
  this.orderService.GetItemDetails(this.oRequest).subscribe(
    lstOrderItem => {
      this.lstOrderItem = lstOrderItem;
      var sData = "";
      if (this.lstOrderItem.length > 0) {
        sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-left' style='font-weight: bold;' id='div_" + orderId + "'>Product Name</div>"; 
        sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-center' style='font-weight: bold;'>Price</div>";
        sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-4 text-center' style='font-weight: bold;'></div>";
        sData += "<div class='clearfix'></div>";
        var aTag = document.createElement('a');
        for (var i = 0; i < this.lstOrderItem.length; i++) {
            sData += "<div style='background-color:#fff;padding:10px 0;'>";
            sData += "<div class='col-4 col-sm-4 col-lg-4 col-xs-4 col-md-4'>";
            sData += "<span style='text-align: justify;'>" + this.lstOrderItem[i].productName + "</span>"; /*<b style='color:red;' > (" + this.lstOrderItem[i].productType + ") < /b>*/
            sData += "</div>";

            sData += "<div class='col-4 col-sm-4 col-lg-4 col-xs-4 col-md-4 text-center'>";
            sData += "<span><i class='fa fa-inr'></i> " + this.lstOrderItem[i].providerSellingPrice + "</span>";
            sData += "</div>";

            sData += "<div class='col-4 col-lg-4 col-md-4 col-xs-2 text-center' style='font-weight: bold;'>";
            sData += '<a  id="btn_' + this.lstOrderItem[i].orderItemID + '" data-oid=' + this.lstOrderItem[i].orderItemID + ' class="mylink btn btn-success" style="width:70px;">Pending</a>';
            sData += "</div>";
            sData += "</div>";
            sData += "<div class='clearfix'></div>";
        }

        sData += "<div style='background-color:#BFE7FF;padding:15px 0;'>";
        sData += "<div class='col-6 col-sm-6 col-lg-6 col-xs-6 col-md-6' style='font-weight: bold'>Total Billed Amount</div>";
        sData += "<div class='col-2 col-sm-2 col-lg-2 col-xs-2 col-md-2 pull-right text-right'>";
        sData += "<span><b>Price:</b> <i class='fa fa-inr'></i> " + totalAmount + "</span></div>";
        sData += "<div class='clearfix'></div>";
        sData += "</div>";
      }
      else {
        $("#errorMsg").removeClass("hidden");
        $("#errorMsg").addClass("alert-danger");
        $("#errorMsg").html("There was no record found");
      }

      $("#accordionNew" + itemIndex).closest("div").html(sData);
      let children = document.getElementsByClassName("mylink");
      for (let i = 0; i < children.length; i++) {
        children[i].addEventListener("click", (event: Event) => {
          this.ConfirmThisOrder(event);
        });
      }
    },
    error => this.errorMessage = <any>error
  );
}
return false;
}