基于 Nexaddo 的帖子,我将在这里详细说明。
给定一个组件:
@Component({
selector: 'app-modal',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
data = "oldData";
@ViewChild() template0:TemplateRef<any>;
constructor() { }
ngOnInit() {
}
}
TempalteRef 顾名思义是一个模板引用。 @ViewChild() 只是说“模板在我的视图中”,如果您将模板从调用传递给 MyComponent,则可以使用 @ContentChild() 或 @Input()。
当你在你的组件模板中调用它时(./my.component.html 这里),在大多数情况下你会这样做:
<ng-template #template0>
<p>Lorem Ipsum...</p>
<p>{{data}}</p>
<p>Lorem Ipsum...</p>
</ng-template>
<ng-container *ngTemplateOutlet="template0">
</ng-container>
这里,对 template0 的调用将从组件上下文中插入 data,因为其中的所有模板共享相同的上下文。但是您可以像这样指定另一个上下文:
<ng-container *ngTemplateOutlet="template0;context=newCtx">
</ng-container>
发件人:
export class MyComponent implements OnInit {
data = "oldData";
newCtx = {data = "newData"};
...
}
像这样,“newData”将被插值而不是“oldData”。
现在,您确实意识到 newCtx 具有 any 作为类型,这就是 TemplateRef<any> 的来源。在大多数情况下,你可能会觉得它没问题,但为了可重用性或只是为了编译器检查,你可以明确这个上下文应该是哪个类:TemplateRef<CustomContextClass>,你必须像这样声明你的上下文:@987654333 @(当然也可以是 CustomContextClass 的任何子类)。
src:https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/ 和 https://blog.mgechev.com/2017/10/01/angular-template-ref-dynamic-scoping-custom-templates/