如何解决你如何将父模板与子数据Angular 11
所以我有两个 Angular 组件,一个父组件和一个子组件。我想做以下事情:
- 在引用的父组件中定义一个ng-template 子函数/变量
- 将该模板作为参数传递给 子组件,以及
- 让子组件显示这个 使用自己的实例数据的模板。
App.Component(父级)
import { Component } from "@angular/core";
@Component({
selector: "my-app",templateUrl: "./app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent {}
<reusable-component [customTemplate]="parentTemplate"></reusable-component>
<ng-template #parentTemplate>
<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>
子组件(可重用组件)
import { Component,Input,OnInit,TemplateRef } from "@angular/core";
@Component({
selector: "reusable-component",templateUrl: "./reusable-component.component.html",styleUrls: ["./reusable-component.component.css"]
})
export class ReusableComponentComponent implements OnInit {
@Input() public customTemplate!: TemplateRef<HTMLElement>;
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";
}
}
<ng-container [ngTemplateOutlet]="customTemplate || defaultTemplate">
</ng-container>
<ng-template #defaultTemplate>
Hello,zuko here!
</ng-template>
如何为我的父模板提供来自该子组件的函数/实例变量?
这是一个Stackblitz with the whole project
解决方法
大多数情况都很好。用于传递数据...
让我们首先开始定义要在子组件中传递的数据
子组件 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>
现在,我们使用 let-
属性来接收父级中的参数
父组件html
<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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。