在使用angular进行开发的时候,经过属性绑定向组件内部传值的方式,有时候并不能彻底知足需求,好比咱们写了一个公共组件,可是某个模板使用这个公共组件的时候,须要在其内部添加一些标签内容,这种状况下,除了使用ngIf
/ngSwitch
预先在组件内部定义以外,就能够利用ngTemplateOutlet
指令向组件传入内容.vue
ngTemplateOutlet
指令相似于angularjs中的ng-transclude
,vuejs中的slot
.angularjs
ngTemplateOutlet
是结构型指令,须要绑定一个TemplateRef
类型的实例.app
使用方式以下:this
@Component({ selector: 'app', template: ` <h1>Angular's template outlet and lifecycle example</h1> <app-content [templateRef]="nestedComponentRef"></app-content> <ng-template #nestedComponentRef let-name> <span>Hello {{name}}!</span> <app-nested-component></app-nested-component> </ng-template> `, }) export class App {} @Component({ selector: 'app-content', template: ` <button (click)="display = !display">Toggle content</button> <template *ngIf="display" *ngTemplateOutlet="templateRef context: myContext"> </template> `, }) export class Content { display = false; @Input() templateRef: TemplateRef; myContext = {$implicit: 'World', localSk: 'Svet'}; } @Component({ selector: 'app-nested-component', template: ` <b>Hello World!</b> `, }) export class NestedComponent implements OnDestroy, OnInit { ngOnInit() { alert('app-nested-component initialized!'); } ngOnDestroy() { alert('app-nested-component destroyed!'); } }
代码中除了根组件外定义了两个组件spa
app-content
app-nested-component
app-content
组件接收一个TemplateRef
类型的输入属性templateRef
,并在模板中将其绑定到了ngTemplateOutlet
指令,当组件接收到templateRef
属性时,就会将其渲染到ngTemplateOutlet
指令所在的位置.code
上例中,app-content
组件templateRef
属性的来源,是在根组件的模板内,直接经过#
符号获取到了app-nested-component
组件所在<ng-template>
的引用并传入的.component
在实际应用中,除了这种方式,也能够直接在组件内部获取TemplateRef
类型的属性并绑定到ngTemplateOutlet
指令.ci
好比在容器组件为模态框的状况下,并不能经过模板传值,就能够使用下面这种方式:开发
@ViewChild('temp') temp: TemplateRef<any> openDialog(){ this.dialog.open(ViewDialogComponent, {data: this.temp) }
在容器组件中还能够定义被传递内容的上下文(上例app-content
组件中的myContext
属性),其中的$implicit
属性做为默认值,在被传递的内容中能够以重命名的方式访问(上例let-name
),对于上下文中其余的属性,就须要经过let-属性名
的方式访问了.it