Javascript 如何在父模板中添加子数据(11)
所以我有两个角度分量,一个是父项,一个是子项。我想做以下工作:Javascript 如何在父模板中添加子数据(11),javascript,html,angular,ng-template,ngtemplateoutlet,Javascript,Html,Angular,Ng Template,Ngtemplateoutlet,所以我有两个角度分量,一个是父项,一个是子项。我想做以下工作: 在引用的父组件中定义ng模板 子函数/变量 将该模板作为参数传递给 子组件,以及 让子组件显示以下内容: 模板使用自己的实例数据 应用程序组件(父级) 从“@angular/core”导入{Component}; @组成部分({ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, 样式URL:[“/app.component.css”] }) 导出类AppComponent{} 当
从“@angular/core”导入{Component};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:[“/app.component.css”]
})
导出类AppComponent{}
当前颜色为{currentColor}
将背景颜色更改为红色
将背景颜色更改为绿色
大多数事情都很好。用于传递数据
让我们首先开始定义要在子组件中传递的数据
子组件TS
currentColor = "white";
constructor() {}
ngOnInit() {}
changeColorToRed() {
const red = "#FF0000";
document.body.style.background = red;
this.currentColor = "red";
}
changeColorToGreen() {
const green = "#00FF00";
document.body.style.background = green;
this.currentColor = "green";
}
data = { currentColor: this.currentColor, changeColorToRed: this.changeColorToRed, changeColorToGreen: this.changeColorToGreen };
现在,我们将包含数据的上下文传递给模板。使用*ngTemplateOutlet
而不是[ngTemplateOutlet]
来支持链接
子组件html
<ng-container *ngTemplateOutlet="customTemplate || defaultTemplate; context: data">
</ng-container>
<reusable-component [customTemplate]="parentTemplate"></reusable-component>
<ng-template #parentTemplate let-currentColor="currentColor" let-changeColorToRed="changeColorToRed" let-changeColorToGreen="changeColorToGreen">
<p>Current color is {{currentColor}}</p>
<button (click)="changeColorToRed()">
CHANGE BACKGROUND COLOR TO RED
</button>
<button (click)="changeColorToGreen()">
CHANGE BACKGROUND COLOR TO GREEN
</button>
</ng-template>
感谢您的回复!!我必须单独添加每个变量吗?我们使用的是一个大文件,最好是一次获取组件本身及其所有成员变量。您可以将所有内容包装在一个对象中,并使用一个
let-
属性来接收该对象。我是否需要做任何额外的事情才能让ViewChild使用此模板?在自定义模板和默认模板中,我都有一个在子组件中尝试访问的模板。我使用@ViewChild('container',{static:false})public readonly containerRef!访问它:ElementRef;这在自定义模板中总是返回undefined,但在defaultTemplate中效果很好