【问题标题】:Angular 5: order html tags inside componentAngular 5:在组件内订购 html 标签
【发布时间】:2018-02-01 06:21:17
【问题描述】:

我需要根据一些输入标志在我的组件中排序 html 元素,如下所示:

如果标志为真:

<i>...</i><span>...</span>

其他:

<span>...</span><i>...</i>

每个标签都有很多绑定,我认为这是错误的 - 只需创建 2 个具有不同顺序的模板。 那么,我怎样才能以有角度的方式实现呢?

此时我找到了这个解决方案:

<ng-container *ngIf="invert; then templateInvert else templateRegular"></ng-container>

<ng-template #templateLabel>
  ...
</ng-template>
<ng-template #templateCheckbox>
  ...
</ng-template>

<ng-template #templateRegular>
  <ng-container *ngTemplateOutlet="templateCheckbox"></ng-container>
  <ng-container *ngTemplateOutlet="templateLabel"></ng-container>
</ng-template>
<ng-template #templateInvert>
  <ng-container *ngTemplateOutlet="templateLabel"></ng-container>
  <ng-container *ngTemplateOutlet="templateCheckbox"></ng-container>
</ng-template>

现在,我想知道是否有一种方法可以更轻松地做同样的事情。

对不起,我的英语不好,谢谢你的提前。

【问题讨论】:

标签: angular angular2-template angular5


【解决方案1】:

做这样的事情:

<div *ngIf='yourFlag'></div>
<div *ngIf='!yourFlag'></div>

或像这样(默认 css 'display:none;'):

<div [class.show]='yourFlag'></div>
<div [class.show]='!yourFlag'></div>

【讨论】:

  • 已经做到了,但是这样我应该用很多绑定来复制 html 标签,每次我需要更改模板时,我应该在 2 个地方这样做。是否存在 DRY 方式?
  • @HouseM.D.另一种方式 - 创建简单的组件并使用 ngIf 调用它
  • 是的,这也是解决方案,谢谢。但我不喜欢它。我想找到更简单的方法。
猜你喜欢
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 2014-03-16
  • 1970-01-01
相关资源
最近更新 更多