将Select2与Angular2组件集成的任何示例?

and*_*cwk 9 jquery-select2 angularjs-select2 angular

我一直试图找到一个如何将Select2集成到角度2组件中的演示/示例.

我的最终目标是使用select 2 ajax功能填充下拉列表,因为我开始在选择框中键入https://select2.github.io/examples.html#data-ajax

到目前为止,我的谷歌忍者权力让我失望:(

select2集成失败的例子......还有其他建议吗?

pre*_*pic 0

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

网页:

<select multiple="multiple" style="display: none;">
    <option *ngFor="#item of people" [value]="item.id">
        {{item.name}}
    </option>
</select>
Run Code Online (Sandbox Code Playgroud)

在 TypeScript 中初始化ngAfterViewInit

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

并且特殊的魔法功能可以将_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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它只是为了设置输入元素的样式而设计的。对于动态添加的元素(选择、选择器),您可能需要捕获一些事件并再次施展魔法。