Angular 2 ng-template不在组件内的dom中呈现

时间:2017-04-20 21:17:58

标签: angular ng-template

我有一个像这样的组件

import {Component, OnInit} from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'details',
    templateUrl: 'details.component.html',
    styleUrls: ["./details.component.scss"],
})
export class DetailsComponent {

    constructor(
        private modalService: NgbModal
    ) {
    }

    open(content) {
        this.modalService.open(content).result.then((result) => {
            console.log("closed");
        }, (reason) => {
            console.log("dismissed");
        });
    }

}

html是,注意顶部的popover组件

<popover></popover>
<div class="row">
    <div class="col">
        <table class="table">
            <thead>
                <th>Action</th>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <button (click)="open(popover)"> open </button>
                    </td>
                </tr>

            </tbody>
        </table>
    </div>
</div>

open组件只是一个显示html的组件

import {Component, OnInit} from '@angular/core';

@Component({
    selector: 'popover',
    templateUrl: 'popover.component.html',
    styleUrls: ["./popover.component.scss"],
})
export class PopOverComponent {

    constructor(
    ) {
    }

}

和popover组件的html

<ng-template #popover let-c="close" let-d="dismiss">
    <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
      <p>One fine body&hellip;</p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>
    </div>
</ng-template>

我的问题是当我将ng-template包裹在测试中时,h1测试元素不会在dom中呈现。更明确地说,ng-template没有呈现我需要将#popover传递给open函数来打开popover。

当我删除ng-template时,我可以看到h1测试。我需要在dom中渲染ng-template,并且我将i放入一个组件中,因为popover组件中有很多html。

知道为什么这样做会这样吗?

1 个答案:

答案 0 :(得分:2)