0

我想在我的角度库中简化开发人员的体验。这就是为什么我试图使用带有特定选择的 ng-content,这些选择会自动填充,而无需开发人员添加类。

例子:

应用

app.component.html

<lib-frame-component>
   <lib-panel-component [modal]="true"></lib-panel-component>
</lib-frame-component> 

图书馆

lib-frame-component.html

 <!-- developper should not need to use class="modals-content" to include lib-panel-component(s) -->
 <ng-content select='.modals-content'></ng-content> 

库框架组件.ts

// get lib-panel-components inserted by the developper
@ContentChildren( LibPanelComponent, { descendants: false } ) directPanels: QueryList<PanelComponent>;
...
// Do something like that somewhere in the life cycle...
this.directPanels.forEach(( panelComponent: LibPanelComponent) => {
  if ( panelComponent.modal === true ) {
     // TODO : code to insert in ng-content.modals-content
  }
} 

我怎样才能做到这一点 ?

4

2 回答 2

0

您不能以编程方式更改内部的投影内容,ng-content因为它并不意味着以这种方式工作。如果你想缩小显示的范围,你需要想出一个更具体的选择器,例如:

<ng-content select="lib-panel-component[shown]"></ng-content>

然后,使用您的库的任何人都可以指定需要显示的内容,如下所示:

<lib-frame-component>
 <!-- this will be projected -->
 <lib-panel-component [modal]="true" shown></lib-panel-component>

 <!-- this will not be projected -->
 <lib-panel-component></lib-panel-component>
</lib-frame-component> 

或者,如果您坚持以编程方式更改投影内容的内容(不建议),您可以@Input向其中添加一个属性LibPanelComponent,然后您可以在其中进行更改lib-frame-component.ts

this.directPanels.forEach(( panelComponent: LibPanelComponent) => {
  if ( panelComponent.modal === true ) {
     panelComponent.hidePanelContent = true;
  }
} 

然后,您需要将 的组件标记包装LibPanelComponent在一个带有 的容器中*ngIf,例如:

<ng-container *ngIf="!hidePanelContent">
<!-- LibPanelComponent markup -->
</div>

<lib-panel-component></lib-panel-component>第二种方法会在 DOM 中留下一堆空组件。

于 2022-01-18T20:35:17.617 回答
0

https://angular.io/guide/content-projection

尝试浏览官方文档。

如果您不在 ng-content 上使用 select,默认情况下,它将采用不会在 ng-content 中填充的内容。

于 2022-01-18T20:19:40.570 回答