Angular 2 ngSwitch 指令,内容相同

标签 angular angular2-directives

我有一个 ngSwitch 可以将指令更改为我需要的。每个case里面都有完全相同的代码(大约100行)。

<div [ngSwitch]="i + 1">
  <div *ngSwitchCase="1" directive1> Same content, many divs, many ngFor.. </div>
  <div *ngSwitchCase="2" directive2> Same content, many divs, many ngFor.. </div>
  <div *ngSwitchCase="3" directive3> Same content, many divs, many ngFor.. </div>                    
</div>

到目前为止工作正常,但我有许多未使用的代码,并且必须在所有情况下更改简单的事情(目前有 10 个)。

有没有办法在案例中使用相同的内容或将指令定义切换为更舒适的方式?

我尝试将内容导出到自定义组件并将其导入其中,但这会导致很多问题(我有大约 50 个 @Input,并且需要一个大型服务来在父组件和所有其他兄弟组件之间进行通信)

最佳答案

更新 Angular 5

ngOutletContext 已重命名为 ngTemplateOutletContext

另请参阅https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

原创

<ng-template #content let-items let-idx="index">
 Same content, many divs, many ngFor..
</ng-template>

<div [ngSwitch]="i + 1">
  <div *ngSwitchCase="1" directive1><ng-container *ngTemplateOutlet="content; context: {$implicit: myData, index: i}"></ng-container></div>
  <div *ngSwitchCase="2" directive2><ng-container *ngTemplateOutlet="content; context: {$implicit: myData, index: i}"></ng-container></div>
  <div *ngSwitchCase="3" directive3><ng-container *ngTemplateOutlet="content; context: {$implicit: myData, index: i}"></ng-container></div>                    
</div>

另请参阅https://angular.io/docs/ts/latest/api/common/index/NgTemplateOutlet-directive.html

关于Angular 2 ngSwitch 指令,内容相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44499125/

相关文章:

angular - 使用 get set 进行单元测试 Angular @Input()

angular - 实现操作 Dom 的第 3 方库的正确方法是什么?

Angular2使用父组件中的单击事件切换子组件中的类

angular - 打开第二个时关闭下拉菜单/document.click被点击Angular 5阻止

Angular 2 RC2 新形式

javascript - Angular Material Checkbox 不会改变选中的状态

angular - 如何在 TypeScript (Angular 2) 中制作多行注释

node.js - 如何动态呈现 pug 文件而不是使用静态 angular-cli index.html?

json - 导入json; typescript 错误 : Module has no exported member

angular - 在 child 中获取父指令