Angular NgTemplateOutlet的一个例子

421 阅读1分钟

NgTemplateOutlet:Inserts an embedded view from a prepared TemplateRef.

语法:

<ng-container *ngTemplateOutlet=“templateRefExp; context: contextExp”>

看个例子:

@Component({
  selector: 'ng-template-outlet-example',
  template: `
    <ng-container *ngTemplateOutlet="greet"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="svk; context: myContext"></ng-container>
    <hr>

    <ng-template #greet><span>Hello</span></ng-template>
    <ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>
    <ng-template #svk let-person="localSk"><span>Ahoj {{person}}!</span></ng-template>
`
})
export class NgTemplateOutletExample {
  myContext = {$implicit: 'World', localSk: 'Svet'};
}

运行时,*ngTemplateOutlet="greet"处的代码被<ng-template #greet>指定的模板所取代:

运行时的html如下图所示:

可以通过语法context: object从消费者端传递数据给template:

如果只传一个字段给模板,传递的参数可以不指定具体名称,直接用$implicit代替。如果需要传递多个字段,在模板里使用let- = "b"传递参数,其中a为模板里{{}}中使用的参数名,而b为传递给模板的参数中的字段名。a和b必须一一对应。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":