【问题标题】:Angular 2 ngSwitch directive, same contentAngular 2 ngSwitch 指令,内容相同
【发布时间】:2017-11-13 21:52:25
【问题描述】:

我有一个 ngSwitch 可以将指令更改为我需要的。每个案例内部都是完全相同的代码(大约 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 个 @Inputs 并且需要大型服务来在父组件和所有其他姐妹和兄弟组件之间进行通信)

【问题讨论】:

  • 如果到处都有相同的内容,为什么要这样做?
  • @GünterZöchbauer 因为我需要不同的指令来根据索引“i”触发特定事件。例如。循环 1 之外的元素应该是可点击的,循环 2 之外的元素应该是可拖动的,循环 3 之外的元素应该有鼠标悬停

标签: angular angular2-directives


【解决方案1】:

更新 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

【讨论】:

  • Ty,会试试的。上下文定义让我有点困惑,但通过文档我会得到它。稍后会接受您的回答。
  • 您可以将对象作为上下文传递以在模板中使用。如果您只声明像let-items 这样的变量,则分配$implicit。具有其他名称的属性需要显式分配,例如 let-idx="index"。这样,您可以将模板中上下文对象的值用作itemidx,例如&lt;div *ngFor="let item of items"&gt; 迭代myData
  • 工作就像一个魅力,我理解它,ty。
【解决方案2】:

我知道问题已经得到解答,但还有另一种方法。

使用以下模板创建一个组件,比如app-component

<ng-template>
 Same content, many divs, many ngFor..
</ng-template>

创建一个通用指令,比如说masterDirective,它可以有条件地应用其他指令 到元素,

然后这样配置

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 2018-01-17
    • 2019-04-08
    • 2019-05-28
    • 2016-10-25
    • 2017-06-08
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多