繁体   English   中英

Angular2 - 使用子组件作为属性的值

[英]Angular2 - using child component as value of an attribute

我希望在用户点击输入字段时显示一个弹出窗口,该字段工作正常,但我希望该弹出窗口的数据内容属性来自子组件的模板。 这是一个例子:

parent.ts

import {Component,AfterViewInit} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChildComponent} from './child_test.ts';


@Component({
    selector: 'app',
    template: `<input type='text' data-toggle="popover" data-trigger="focus" data-placement="bottom" [attr.data-content]="getPopoverContent()" />`,
    providers: [ChildComponent]
})
class AppComponent implements AfterViewInit{
    constructor(private _child: ChildComponent) {}

    getPopoverContent(){
        return this._child; //returning empty object instead of child template
    }
    ngAfterViewInit(){
        $("input").popover();
    }

}

bootstrap(AppComponent);

child.ts

import {Component} from 'angular2/core';

@Component({
    selector: "child-component",
    template: "<div>Popover content from child.</div>"
})
export class ChildComponent{};

我应该使用DynamicComponentLoader而不是依赖注入吗? 如果是的话那我怎么能实现呢?

这是一个解决方法:

将临时变量分配给要显示的组件

<transaction-filter #popoverComponent></transaction-filter>

要点:上面的组件必须在其定义中公开ElementRef

constructor(public el: ElementRef) {}

创建将显示弹出窗口的元素

<button class="btn-sm btn-link text-muted"
    data-animation="true"
    data-placement="bottom"
    title="Create Rule"
    [popover]="popoverComponent">

    Create Rule...
</button>

现在popover指令本身:

/// <reference path="../../typings/tsd.d.ts"/>

import 'bootstrap'

import { Directive, ElementRef, Input} from 'angular2/core'

declare var $: JQueryStatic;

@Directive({
    selector: '[popover]',
})
export class PopoverDirective {
    @Input('popover') _component: any
    _popover: JQuery

    constructor(private _el: ElementRef) { }

    ngOnInit() {
        // Hide the component
        this._component.el.nativeElement.style.display = "none"

        // Attach it to the content option
        this._popover = $(this._el.nativeElement)
            .popover({
            html: true,
            content: this._component.el.nativeElement
        })

        // When the below event fires, the component will be made visible and will remain
        this._popover.on('shown.bs.popover', () => {
            this._component.el.nativeElement.style.display = "block"
        })
    }
}

一个问题是绑定到属性会将值字符串化

 [attr.data-content]

因此这种方法不起作用。

似乎Bootstrap popover需要一个字符串,因此这样会很好,但是对一个Angular组件进行字符串化并不会给它提供HTML。

暂无
暂无

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

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