代码之家  ›  专栏  ›  技术社区  ›  JSmith

如何在不使用*ngIf的情况下有条件地选择组件

  •  1
  • JSmith  · 技术社区  · 2 年前

    我在组件内部循环消息,并希望在不使用的情况下选择适当的组件 *ngIf 。目前代码如下所示:

    <div *ngFor="let message of messages">
        <app-message-1 *ngIf="message.type === 1" [message]="message"></app-message-1>
        <app-message-2 *ngIf="message.type === 2" [message]="message"></app-message-2>
    </div>
    

    我在想一些看起来更像哈希图事件的东西,尽管这是不可能的(伪代码):

    html:

    <div *ngFor="let message of messages">
        getComponent(message.type, message);
    </div>
    

    ts:

    componentsHash = {
      1:Message1Component,
      2:Message2Component
    }
    
    getComponent( type:number, message:message ) {
    
      return ( new componentsHash[ type ]( message ) )
    
    }
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   iamaword    2 年前

    你可以使用一个指令来完成类似的事情: https://fireflysemantics.medium.com/creating-a-dynamic-component-with-a-directive-7211bfe22921 .

    如果你不想走这条路,那么我建议你创建一个基于显示的组件,在类型上使用*ngSwitch。该组件可能是一个相当“愚蠢”的组件,其全部功能是显示传递的数据。如果你走这条路,你也可以使用changedetectionStrategy.opush来提高它的性能,这取决于你的显示组件的预期功能

        2
  •  0
  •   Kartik Gogia    2 年前

    你可以做的是,你只能创建一个组件,并在该组件中传递消息,如下所示,无需创建多个组件。

    <div *ngFor="let message of messages">
    <app-message [message]="message"></app-message>
    </div>
    

    现在,在应用程序消息组件模板(app-message.component.html)文件中,您可以根据消息类型使用ngIf,如下所示:

    <div *ngIf="message.type == 1">
     //Your content goes here
    </div>
    
    <div *ngIf="message.type == 2">
     //Your content goes here
    </div>
    

    这样,只需使用一个组件就可以实现您想要的目标。