简体   繁体   English

Angular2:为Typescript中的select设置更改属性

[英]Angular2: Set change attribute for select in Typescript

I am dynamically creating dropdowns in my typescript code. 我在我的打字稿代码中动态创建下拉列表。 That works perfectly fine. 那很好。 However, I cannot figure out how to set the "onchange" event for the dropdowns - so that it triggers whenever the value of the dropdown is changed. 但是,我无法弄清楚如何为下拉菜单设置“ onchange”事件-因此,只要下拉列表的值发生更改,它就会触发。

That's my ts code so far: 到目前为止,这是我的ts代码:

  private createDropDown() {
    const parent = document.getElementById('dropdown-container');
    const sel: any = document.createElement('select');
    sel.setAttribute('id', 'bbCount' + this.bbCount);
    sel.setAttribute('class', 'labelDropdown');
    $('labelDropdown').on('change', e => this.onDropdownChange(e));
    for (let i = 0; i < 8; i++) {
      const opt: any = document.createElement('option');
      opt.setAttribute('text', this.labels[i].value);
      opt.setAttribute('value', String(this.labels[i].id));
      opt.innerText = this.labels[i].value;
      sel.appendChild(opt);
    }
    parent.appendChild(sel);
  }

  public onDropdownChange(e) {
    console.log('event', e);
  }

html: HTML:

  <div style="width: 100%" id="dropdown-container">
  </div>

I tried several approaches, the last one was 我尝试了几种方法,最后一种是

$('labelDropdown').on('change', e => this.onDropdownChange(e)); $('labelDropdown')。on('change',e => this.onDropdownChange(e));

However, this.onDropdownChange(e) is never called or just when the dropdown is created and not when the value is changed. 但是,永远不会调用this.onDropdownChange(e)或仅在创建下拉列表时调用,而不是在更改值时调用。

Does anyone know how I can set the change event on the select inside my typescript code? 有谁知道我如何在打字稿代码中的select上设置change事件?

You are doing a lot of things counter to recommended way of doing it with Angular. 您正在做很多事情,与推荐的Angular方法背道而驰。 In this example, you're adding HTML with jQuery, so Angular won't know about these components. 在此示例中,您将使用jQuery添加HTML,因此Angular将不了解这些组件。 And if you hook regular JavaScript events, it's outside of angular's knowledge. 而且,如果您钩住常规的JavaScript事件,则超出了angular的了解。 You could wrap it in a zone, with some refactoring. 您可以将其包装在一个区域中,并进行一些重构。 Or you could do it the recommended way - create an angular dropdown component (can be a simple wrapper around your jQuery), and create an injector that injects this component dynamically. 或者,您也可以按照推荐的方式进行操作-创建一个有角度的下拉组件(可以是jQuery的简单包装器),并创建一个可以动态注入该组件的注入器。

Another thing is that angular's change would work an an actual select or whatever. 另一件事是,角度的更改将对实际的选择有效。 So you can make this component implement eg custom input control. 因此,您可以使该组件实现例如自定义输入控件。 Then you could hook to it's (change) or (ngModelChange) events in your component. 然后,您可以在组件中挂钩到它的(change)或(ngModelChange)事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM