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:
- Setup context use
*ngTemplateOutlet
mini syntax:ng-container *ngTemplateOutlet="tpl; context: item"
.context
is an expression, hereitem
is a variable. Ifitem
's shape not matches template expects, or ifitem
is a plain value, remember context must be object, call a transform function is very helpfulcontext: toObject(item)
.
Angular expression supports complex expressions likecontext: {title: item}
. - 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>
, herefoo
is a field of current component.
In other words, in template definitions, binding works on current component context, remap variables uselet-xxx
to get value fromngTemplateOutlet
passed in context.
ngComponentOutlet
Like ngTemplateOutlet
but create a host view from a component class.
<ng-container *ngComponentOutlet="ColorComponent"></ng-container>
- 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.
- Unlike template outlet, no context to set component's properties, all value must passed through
DI
with customizedInjector
.
If we don't use ngComponentOutlet
, maybe we can set component instance properties by hand.
网友评论