ngTemplateOutlet 指令用于标识指定的 DOM 元素作为视图容器,然后自动地插入设定的内嵌视图,而不用像 ViewContainerRef 章节中示例那样,需要手动创建内嵌视图。 指令,大大减轻了我们的工作量,接下来让我们看一下 ngTemplateOutlet 指令的定义: @Directive({selector: '[ngTemplateOutlet]'}) export class NgTemplateOutlet implements OnChanges { // TODO(issue/24571): remove '!'. @Input() public ngTemplateOutlet ! 指令除了支持 ngTemplateOutlet 输入属性之外,还支持 ngTemplateOutletContext 输入属性。
指令 ngTemplateOutlet 的作用 该指令用于基于已有的 TemplateRef 对象,插入对应的内嵌视图。 在应用 NgTemplateOutlet 指令时,我们可以通过 [ngTemplateOutletContext] 属性来设置 EmbeddedViewRef 的上下文对象。 ngTemplateOutlet 的使用 import { Component } from '@angular/core'; @Component({ selector: 'app-root', </ng-template> <div [ngTemplateOutlet]="atpl">
专门研究一下ngTemplateOutlet用法!!!! 在我遇到的情况中,有两种时候会用到ngTemplateOutlet。 1、需要要自定义标题或页脚的内容。 2、递归组件使用时,要用到ngTemplateOutlet 来切换节点上的组件。 比如要定义菜单组件,涉及到两类组件,1是叶子菜单项,2是文件夹菜单项。 (向ngTemplateOutlet 传入 context: myContext”) ? 上下文传递很重要。 ngTemplateOutlet 不仅用于绑定元素,还负责把子组件中的一个数据上下文传递进去. 5、模板元素如何使用上下文? } from '@angular/core'; /// 主页面 @Component({ selector: 'app-root', template: `
image.png 核心是 ngTemplateOutlet 我们通过源码来看是如何实现的。 关键字 ngTemplateOutlet 先看模板,ngTemplateOutlet 是一个指令,它接收模板变量,可以实现模板的动态渲染, 在这里,如果定义了 nzTemplate 变量就使用它,否则用默认的
我们需要使用 @ContentChild 访问模板,并使用ngTemplateOutlet 来显示它: @Component({ selector: 'wrapper', template: ` 'Hide' : 'Show' }} </button>
compiler: 编译选项useDebug从v4版本已经弃用且无效,现在移除; common: NgFor在v4版本被弃用,现用NgForOf代替,但不影响在模版中使用*ngFor; common: NgTemplateOutlet #ngOutletContext在v4版本被弃用,使用NgTemplateOutlet#ngTemplateOutletContext代替; core: ErrorHandler在v4版本被弃用,现在它不再带参数
Toggle 组件 <toggle>组件能够通过ContentChild装饰器得到关于<ng-template>的引用,之后会赋予模板在渲染时所需要的状态,代码如下: <ng-container *ngTemplateOutlet : this.toggle, fns: { toggle: this.toggle } }"> </ng-container> 这里<ng-container>被当做一个占位符来使用,之后你可以使用*ngTemplateOutlet
使用ng-container定义我们的投影区块 使用ngTemplateOutlet指令来渲染ng-template元素。 通过内置的动态指令*ngIf来控制是否渲染投影。
<ng-container [ngTemplateOutlet
Toggle 组件 <toggle>组件能够通过ContentChild装饰器得到关于<ng-template>的引用,之后会赋予模板在渲染时所需要的状态,代码如下: <ng-container *ngTemplateOutlet : this.toggle, fns: { toggle: this.toggle } }"> </ng-container> 这里<ng-container>被当做一个占位符来使用,之后你可以使用*ngTemplateOutlet
指令: connection.component.ts @Component({ selector: 'connection', template: ` <ng-template [ngTemplateOutlet ]="fast.tpl" *ngIf="isFast"></ng-template> <ng-template [ngTemplateOutlet]="slow.tpl" *ngIf="!
解决方法 为了让组件能够控制投射进来的子组件的实例化,我们可以通过两种方式完成:在我们的内容周围使用 <ng-template> 元素及 ngTemplateOutlet,或者使用带有 "*" 语法的结构指令 : 'Show' }} </button>
与您在第1部分中所做的相似,添加所有:CORE_DIRECTIVES: CORE_DIRECTIVES = const [NgClass, NgFor, NgIf, NgTemplateOutlet,