簡體   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