在使用angular进行开发的时候,通过属性绑定向组件内部传值的方式,有时候并不能完全满足需求,比如我们写了一个公共组件,但是某个模板使用这个公共组件的时候,需要在其内部添加一些标签内容,这种情况下,除了使用ngif/ngswitch预先在组件内部定义之外,就可以利用ngtemplateoutlet指令向组件传入内容.
ngtemplateoutlet指令类似于angularjs中的ng-transclude,vuejs中的slot.
ngtemplateoutlet是结构型指令,需要绑定一个templateref类型的实例.
使用方式如下:
@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!'); } }
代码中除了跟组件外定义了两个组件
app-content组件接收一个templateref类型的输入属性templateref,并在模板中将其绑定到了ngtemplateoutlet指令,当组件接收到templateref属性时,就会将其渲染到ngtemplateoutlet指令所在的位置.
上例中,app-content组件templateref属性的来源,是在根组件的模板内,直接通过#符号获取到了app-nested-component组件所在<ng-template>的引用并传入的.
在实际应用中,除了这种方式,也可以直接在组件内部获取templateref类型的属性并绑定到ngtemplateoutlet指令.
比如在容器组件为模态框的情况下,并不能通过模板传值,就可以使用下面这种方式:
@viewchild('temp') temp: templateref<any> opendialog(){ this.dialog.open(viewdialogcomponent, {data: this.temp) }
在容器组件中还可以定义被传递内容的上下文(上例app-content组件中的mycontext属性),其中的$implicit属性作为默认值,在被传递的内容中可以以重命名的方式访问(上例let-name),对于上下文中其他的属性,就需要通过let-属性名的方式访问了.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
解决三元运算符 报错“SyntaxError: can''t assign to conditional expression”
解决angular 使用原生拖拽页面卡顿及表单控件输入延迟问题
使用 Angular RouteReuseStrategy 缓存(路由)组件的实例代码
分享Angular http interceptors 拦截器使用(推荐)
网友评论