如何将Select2与Angular2组件集成?是否有任何示例?

9
我一直在寻找一个将Select2集成到Angular 2组件中的演示/示例。
我的最终目标是使用Select2的ajax功能来在我开始在选择框中输入时填充下拉列表,即 https://select2.github.io/examples.html#data-ajax
到目前为止,我的Google忍者技能已经失败了:(
如果没有Select2集成的示例...是否有其他建议?
2个回答

3
当我开始寻找Angular2中Select2多下拉框示例时,我找不到我想要的那种。我意识到有时候Google的忍者能力并不起作用。我不得不自己编写它。然而,我想分享它,不要再让Google的忍者能力失效。 :) 这里是Plunker链接,可以查看工作演示 核心是将Select2包装在一个Angular组件中。
export class DummySelect {
  constructor(private id: string){
    $(id).select2({
      width: '100%',
      ajax: {
        url: 'https://api.github.com/search/repositories',
        datatype: 'json',
        delay: 250,
        data: function(params: any){
          return {
            q: params.term
          };
        },
        processResults: function(data:any, params: any){
          return {
            results:
              data.items.map(function(item) {
                return {
                  id: item.id,
                  text: item.full_name
                };
              }
            )};
          },
        cache: true  
      },
      placeHolder: 'Search...',
      minimumInputLength: 2 
    })
  }

  getSelectedValues(private id: string){
    return $(id).val();
  }
}

0

让我们看看我如何使用select2。我的目的是初始化select2并添加_ngcontent-属性,以便在我的范围内通过scss进行样式设置。

HTML:

<select multiple="multiple" style="display: none;">
    <option *ngFor="#item of people" [value]="item.id">
        {{item.name}}
    </option>
</select>

在 TypeScript 中在 ngAfterViewInit 上进行初始化:

ngAfterViewInit()
{
    var element = (<any>$('select')).select2().siblings('.select2-container')[0];
    var attribute = ObjectHelper.setElementContentAttribute(this.m_elementRef.nativeElement, element, true);
}

还有一些特殊的魔法函数,可以将_ngcontent属性克隆到子元素中。这对于许多第三方库非常有用,因为它们会生成一些动态内容:

public static getAngularElementTag(element: Element): string
{
    var attrs = [].filter.call(element.attributes, at => /^_nghost-/.test(at.name));
    if (attrs.length == 0)
    {
        return null;
    }
    return attrs[0].name.replace("_nghost-", "_ngcontent-");
}


public static setElementContentAttribute(hostElement: Element, targetElement: Element, setRecursive?: boolean): string
{
    var attribute = this.getAngularElementTag(hostElement);
    setRecursive = (setRecursive !== undefined) ? setRecursive : false;
    if (attribute !== null)
    {
        this._setElementContentAttribute(targetElement, setRecursive, attribute);
        return attribute;
    }
    else
    {
        return null;
    }
}

private static _setElementContentAttribute(targetElement: Element, recursive: boolean, attribute) {
    targetElement.setAttribute(attribute, '');
    if (recursive) {
        for (var i = 0; i < targetElement.childElementCount; i++) {
            this._setElementContentAttribute(<Element>targetElement.childNodes[i], recursive, attribute);
        }
    }
}

这个只是用来样式化输入元素的。对于动态添加的元素(选择、选择器),你可能需要捕获一些事件并再次进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接