将嵌套元素放入 ng-content

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

我尝试用一个

<pane />
获得所有
<ng-content />

一个

<pane />
直接位于父元素的根DOM中,另一个位于
<div></div>

内部

父组件 HTML:

<tab style="display: flex; flex-direction: column">
   <pane id="1">Pane 1</pane>
   
   <div>
     <pane id="2">Pane 2</pane>
   </div>
</tab>

子级

Pane
组件 HTML:

Pane in ng-content select="pane" 
<ng-content select="pane" />

<br/>
Others panes:
<ng-content />

结果如下:

ng-content 中的窗格 select="pane" 窗格 1

其他窗格: 窗格 2

我的第一个

<ng-content />
没有捕获嵌套的
<pane />
,它是第二个。

有没有办法在第一个

<pane />
中捕获所有
<ng-content />

这是我的示例:https://stackblitz-starters-j5xukj.stackblitz.io 相关文档:https://angular.dev/api/core/ContentChildren?tab=usage-notes

angular ng-content
1个回答
0
投票

我希望这是预期的输出,我们可以将类作为输入发送到

[select]="pane"
属性选择器,它似乎可以工作!

import { CommonModule } from '@angular/common';
import {
  Component,
  ContentChildren,
  Directive,
  Input,
  QueryList,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Directive({ selector: 'pane', standalone: true })
export class Pane {
  @Input() id!: string;
}

@Component({
  selector: 'tab',
  standalone: true,
  imports: [Pane, CommonModule],
  template: `
    Pane in ng-content select="pane" 
    <ng-content [select]="pane" />
  `,
})
export class Tab {
  pane = Pane;
}

@Component({
  selector: 'example-app',
  standalone: true,
  imports: [Tab, Pane, CommonModule],
  template: `
    <tab style="display: flex; flex-direction: column">
      <pane id="1">Pane 1</pane>
      
      <div>
        <pane id="2">Pane 2</pane>
      </div>
    </tab>
  `,
})
export class ContentChildrenComp {}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ContentChildrenComp, CommonModule],
  template: `
    <example-app/>
  `,
})
export class App {}

bootstrapApplication(App);

堆栈闪电战

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.