angular6.x中ngTemplateOutlet指令的使用示例

发布时间:2020-10-06 22:46:07 作者:chenqiao
来源:脚本之家 阅读:153

在使用angular进行开发的时候,通过属性绑定向组件内部传值的方式,有时候并不能完全满足需求,比如我们写了一个公共组件,但是某个模板使用这个公共组件的时候,需要在其内部添加一些标签内容,这种情况下,除了使用ngIf/ngSwitch预先在组件内部定义之外,就可以利用ngTemplateOutlet指令向组件传入内容.

ngTemplateOutlet指令类似于angularjs中的ng-transclude,vuejs中的slot.

ngTemplateOutlet是结构型指令,需要绑定一个TemplateRef类型的实例.

使用方式如下:

@Component({
 selector: 'app',
 template: `
  <h2>Angular's template outlet and lifecycle example</h2>
  <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!');
 }
 
}

代码中除了跟组件外定义了两个组件

  1. 容器组件:app-content
  2. 传递进去的内容组件:app-nested-component

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-属性名的方式访问了.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. Vue自定义指令的使用示例
  2. zabbix中执行远程主机脚本或指令的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular6 ngtemplateoutlet emp

上一篇:nodeJS微信分享

下一篇:jquery获取input输入框中的值

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》