[Angular 2] Create template with Params

本文介绍了Angular2中如何使用特殊的let语法定义和传递上下文到模板。通过ViewChild装饰器获取视图容器引用,并利用ComponentFactoryResolver创建组件实例。演示了如何通过createEmbeddedView方法将特定的对象作为上下文传递给模板。

Angular 2 templates have a special let syntax that allows you to define and pass a context when they’re being generated.

 

import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ViewChild} from '@angular/core';
import {SimpleService} from "../../serivces/simple.service";
import {WidgetThree} from "../widgets/widget-three.component";

@Component({
    moduleId: module.id,
    selector: 'home',
    templateUrl: 'home.component.html'
})
export class HomeComponent {

    @ViewChild('container', {
        read: ViewContainerRef
    }) container;
    @ViewChild('template') template;

    constructor(private resolver: ComponentFactoryResolver, private simpleService: SimpleService) {
    }

    ngAfterContentInit(){
        const WidgetFactory = this.resolver.resolveComponentFactory(WidgetThree);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
        this.container.createComponent(WidgetFactory);
    }

    onClick(){
        this.container.createEmbeddedView(
            this.template,
            {
                desc: 'Good'
            }
        )
    }

}

 

We pass in an Object "desc: Good",  to the template, in tempalte, we use "let-" keyword to define the variable which we can reference to, and the object will be the 'context' for the template.

<template #template let-desc="desc">
    <h3>tempalte {{desc}}</h3>
    <section>tempalte {{desc}}</section>
    <footer>template {{desc}}</footer>
</template>

 

转载于:https://www.cnblogs.com/Answer1215/p/5901625.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值