美文网首页
Dynamic Insert Views using Templ

Dynamic Insert Views using Templ

作者: forks1990 | 来源:发表于2018-09-20 18:01 被阅读0次

As last article, dynamic insert views needs some routing code, use ngTemplateOutlet and ngComponentOutlet directive removes the routing code.

ngTemplateOutlet

ngTemplateOutlet turns marked element to be ViewContainer, and inserts the embedded view:

@Component({
    selector: 'sample',
    template: `
        <span>I am first span</span>
        <ng-container *ngTemplateOutlet="tpl"></ng-container>
        <span>I am last span</span>
        <ng-template #tpl>
            <span>I am span in template</span>
        </ng-template>
    `
})
export class SampleComponent {}

Pass Context to Template

Context is an object that Template get value from:

<span>Hello: {{name}}</span>

Variable name is a field of context.

Pass context to template need several steps:

  1. Setup context use *ngTemplateOutlet mini syntax: ng-container *ngTemplateOutlet="tpl; context: item". context is an expression, here item is a variable. If item's shape not matches template expects, or if item is a plain value, remember context must be object, call a transform function is very helpful context: toObject(item).
    Angular expression supports complex expressions like context: {title: item}.
  2. Map variables in <ng-template>. like: <ng-template #tpl let-text="title">{{text}}</ng-template>.
    Only mapped context variable can accessed inside template
    Current component context variable still accessible: <ng-template #tpl let-title="title">Item: {{title}} {{foo}}</ng-template>, here foo is a field of current component.
    In other words, in template definitions, binding works on current component context, remap variables use let-xxx to get value from ngTemplateOutlet passed in context.

ngComponentOutlet

Like ngTemplateOutlet but create a host view from a component class.

<ng-container *ngComponentOutlet="ColorComponent"></ng-container>
  1. Pass component class is okay, no need and not the component factory, maybe it is the reason must add the component class to module's entryComponents.
  2. Unlike template outlet, no context to set component's properties, all value must passed through DI with customized Injector.

If we don't use ngComponentOutlet, maybe we can set component instance properties by hand.

相关文章

网友评论

      本文标题:Dynamic Insert Views using Templ

      本文链接:https://www.haomeiwen.com/subject/zjdnnftx.html