根据 parent 中的选项将动态 Html 元素传递给 Angular 中的 child 组件?

pass Dynamic Html element based on options from parent to child component in Angular?

我想根据以下条件将 html 元素从 parent 传递到 child 如果用户单击 parent 中的按钮 child 应显示按钮 如果用户 select chckbox 那么 child 应该显示复选框 这是我的场景

为了解决这个问题,我通过 angular 中的内容投影概念使用 ngTemplateOutletngContent

我在控制台中遇到错误 错误 错误:templateRef.createEmbeddedView 不是函数

我这样试过

  <button (click)="getType('button')">Display button in child</button>
  <div>
  <label>checkbox</label>
  <input type="checkbox" (change)="getType('checkbox')">
  </div>
  <app-child>

  <ng-container [ngTemplateOutlet]="dynamicElement"></ng-container>

        <ng-template #tp2>
        <button>Hey I am button passed dynamically from parent</button>
        </ng-template>

          <ng-template #tp3>
        <label>I am checkbox passed from parent</label>
       <input type="checkbox" (change)="getType('checkbox')">
        </ng-template>

请找link我算https://stackblitz.com/edit/angular-yzzsgs-dnfgaq?file=src/app/app.component.ts

还有其他方法吗?

任何帮助都将不胜感激

提前致谢

修改您的代码如下:

export class AppComponent {

  @ViewChild('tp2') public readonly tp2;
  @ViewChild('tp3') public readonly tp3;

  title = 'Tour of Heroes';
  dynamicElement: any;
  heroes = [
    new Hero(1, 'Windstorm'),
    new Hero(13, 'Bombasto'),
    new Hero(15, 'Magneta'),
    new Hero(20, 'Tornado')
  ];
  myHero = this.heroes[0];

  getType (type) {
    console.log(type);
    if (type == 'button') {
      this.dynamicElement = this.tp2;
    } else {
      this.dynamicElement = this.tp3;
    }
  }
}

顺便说一句,您需要从“@angular/core”导入 ViewChild 指令,并使用它从模板中获取 Ref,以将其传递给 ngTemplateOutlet

你可以使用@ViewChild这个概念;有关更多信息,请查看其 Angular documentation。文档有一个倒计时组件的示例,其中父级在每次父级本身启动时启动其子级。