您如何使用 child 数据 (Angular 11) 水化 parent 模板

How do you hydrate a parent template with child data (Angular 11)

所以我有两个 Angular 组件,一个 parent 和一个 child。我想执行以下操作:

  1. 在引用的 parent 组件中定义一个 ng-template childfunctions/variables
  2. 将该模板作为参数传递给 child 个组件,并且
  3. 让 child 组件显示这个 使用自己的实例数据的模板。

App.Component (Parent)

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>

Child 组件 (reusable-component)

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>

如何为我的 parent 模板提供 child 组件中的 functions/instance 变量?

这是一个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-属性来接收parent

中的参数

父组件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>

Stackblitz