是否可以使 ng-content select="..." 与另一个 ng-content 投影一起使用?

问题描述 投票:0回答:1

我有一个库组件

app-internal
,它使用内容投影和一些选择器 - 这里是
h1
h2
。不,我想为该组件创建装饰器包装器 -
PublicCompoent
,它应该将其内容投影到
InternalComponent
。但是,如果
InternalComponent
使用
<ng-content select="...">
,则不起作用。假设我无法修改
app-internal
组件,是否可以使其工作?

接受

PublicComponent
的内容作为
InternalComponent
的输入至关重要。

示例:

//internal component:

  <div class="internal">
<!--this works -->
    <ng-content></ng-content>

    <ng-content select="h2"></ng-content> <!--this does not work -->
    <ng-content select="h1"></ng-content> <!--this does not work -->
  </div>

//wrapper component
<div class="public">

    WRAPPING START
    <app-internal>
      <ng-content></ng-content>
    </app-internal>
    WRAPPING END
  </div>

//how I would like to actually be able to use it
  <app-public>
      <h1>Hello</h1>
      <h2>there</h2>
  </app-public>

https://stackblitz.com/edit/angular-17-starter-project-al4ddu?file=src%2Fmain.ts

angular
1个回答
0
投票

您可以创建一个

h1
h2
作为代理来将数据传输到内部组件,这种方法非常基本,但是是克服
tags
在深入时不被理解的可能解决方案通过内容投影发送!

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-internal',
  standalone: true,
  template: `
  <div class="internal">
<!--this works -->
    <!-- <ng-content></ng-content> -->

    <ng-content select="h2"></ng-content> 
    <ng-content select="h1"></ng-content> 
  </div>`,
})
export class InternalComponent {}

@Component({
  selector: 'app-public',
  standalone: true,
  template: `<div class="public">
    WRAPPING START
    <app-internal>
      <h1 style="margin: 0px !important;"><ng-content select="h1"></ng-content></h1>
      <h2 style="margin: 0px !important;"><ng-content select="h2"></ng-content></h2>
    </app-internal>
    WRAPPING END
  </div>`,
  imports: [InternalComponent],
})
export class PublicComponent {}

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
  <app-public>
      <h1>Hello</h1>
      <h2>there</h2>
  </app-public>
  `,
  imports: [PublicComponent],
})
export class App {
  name = 'Angular';
}
bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.