动态组件单击事件绑定Angular2

时间:2016-07-01 08:01:05

标签: javascript angular

在我的项目中,我动态加载了一些元素。但是我无法为这些元素生成点击事件。

import {Component, DynamicComponentLoader, Injector} from 'angular2/core';


@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <button (click)="form()">
    View Form
  </button>
    <div id="form" [innerHTML]="">
      Welcome..! Here form component will be loaded.

    </div>
  `,
  directives: []
})
export class App {
    private strForMarkets = "";
    private sbForMarkets: Array<string> = [];
  constructor(public dcl:DynamicComponentLoader, public _injector:Injector) {
  }
  form() {
      var s = ["a", "s", "d", "p"];
      this.sbForMarkets.push("<div><ul>")
      for (var index = 0; index < s.length; index++) {
          var element = s[index];
          this.sbForMarkets.push("<li class='OH liDataLeftFilterMarketsContainer'>");
          this.sbForMarkets.push("<div class='FL sprite_icon expand-icon-market'></div>");
          this.sbForMarkets.push("<div class='expand-text-div CP FT14 LH15' (click)='chill($event)' >" + element + "</div>");
          this.sbForMarkets.push("</li>");
      }
      this.sbForMarkets.push("</ul></div>");
      this.strForMarkets = this.sbForMarkets.join("");
  }

  chill() {
      console.log("Dude... Chill  ");
    }
}

P.S。我尝试过使用动态组件加载器,但只有模板中的所有html才有效。

1 个答案:

答案 0 :(得分:0)

Angular2不处理使用public void onAdd(View v) { EditText name = (EditText)findViewById(R.id.inputName); String nameString = name.getText().toString(); EditText quantity = (EditText)findViewById(R.id.inputQuantity); String quantityString = quantity.getText().toString(); db.addWorkout(new Workout(nameString,quantityString)); } 动态添加的HTML或类似的$(document).ready(function(){ $('a').on('click', function(){ var GetaName = $(this).attr('href').split('#'); $('html,body').animate({scrollTop : $('a[name="'+GetaName[1]+'"]').offset().top},1000); }); }); 只会被忽略并按原样添加。

如果可能,将HTML包装在组件中并使用[innerHTML]="..."代替。有关示例,请参阅Angular 2 dynamic tabs with user-click chosen components