Angular 2中组件的自定义用户模板

Custom user template for a component in Angular 2

本文关键字:用户 自定义 组件 Angular      更新时间:2023-09-26

我有一个组件,它有它的默认模板:

    import {Component} from 'angular2/core';
    @Component({
        selector: 'my-component',
        template: `
            <div class="container">
                <div class="content">
                    <div *ngIf="contentRef.childNodes.length == 0">DEFAULT: <b>{{contentData}}</b></div>
                    <div #contentRef><ng-content select=".content"></ng-content></div>
                </div>
            </div>
        `
    })
    export class MyComponent {
        contentData = "DATA";
    }

我希望用户在使用时能够为组件的某些部分指定自己的模板

import {Component} from 'angular2/core';
    import {MyComponent} from './my.component';
    @Component({
        selector: 'my-app',
        directives: [MyComponent],
        template: `
            <my-component></my-component> 
            <br/>
            <my-component>
                <div class="content">
                    CUSTOM: <i>{{contentData}}</i>
                </div>
            </my-component>
        `
    })
    export class AppComponent { }

它产生以下标记:

<my-app>
        <my-component>
        <div class="container">
            <div class="content">
                <!--template bindings={}--><div>DEFAULT: <b>DATA</b></div>
                <div></div>
            </div>
        </div>
    </my-component> 
        <br>
        <my-component>
        <div class="container">
            <div class="content">
                <!--template bindings={}-->
                <div><div class="content">
                CUSTOM: <i></i>
            </div></div>
            </div>
        </div>
    </my-component>
    </my-app>

因此,组件的"contentData"属性不会在自定义模板中呈现。是否可以以某种方式为自定义模板提供特定的绑定上下文?或者有更好的方法用自定义用户模板来实现这个案例吗?

如何在Angular2中实现数百页的网站展示了一种方法。

这不是官方的解决方案,对我来说,目前看来这可能会在最终发布之前中断。Angular2具有静态构建和解析绑定的强烈倾向。

您可以使用DynamicComponentLoader,也可以不为动态添加的内容构建Angulars绑定功能。