【问题标题】:Create a reusable template which can be used on various pages创建一个可重用的模板,可用于各种页面
【发布时间】:2018-10-29 06:30:48
【问题描述】:

在我的 Angular 5 应用程序中,我需要在每个 HTML 页面上执行此操作

<span *ngIf="item.createTime; else notAvailable">
   &nbsp;{{item.createdTime | date:'medium'}}
</span>

并在页面末尾创建该模板

<ng-template #notAvailable>
    <span class="text-muted f-12" [innerText]="'N/A'"></span>
</ng-template>

在每个 HTML 页面上都重复相同的代码行,因此寻找任何解决方案来帮助我创建一个只有#notAvailable 内容并且可以在每个页面上使用*ngIf 的通用组件/指令?

在之前的angularJS中,我们可以创建一个单独的模板文件并使用,但是在新的angular中,指令中没有HTML可以附加,所以有点困惑如何做到这一点?

有人,请指导我如何实现这一点以及在相应的组件和 HTML 中需要写什么?

【问题讨论】:

  • 只是我的 Dumb Vue 自己在问这个问题,但是组件不适合您的用例吗?
  • 有一个article,这让我更困惑使用哪一个,因为有很多诸如装饰器viewChildViewContainerRefTemplaterefviewRef

标签: html angular angular-ng-if


【解决方案1】:

您可以创建一个组件,例如:CreatedTimeComponent created-time.component.ts

@Component({
  selector: 'app-created-time',
  templateUrl: './created-time.component.html',
  styleUrls: ['./created-time.component.scss']
})
export class CreatedTimeComponent {
  Input()
  createdTime: Date;
}

created-time.component.html

<ng-container *ngIf="createdTime; else notAvailable">
  <span>
     &nbsp;{{createdTime | date:'medium'}}
  </span>
</ng-container>
<ng-template #notAvailable>
  <span class="text-muted f-12">N/A</span>
</ng-template>

some-other.component.html

<h2>My some other component<h2>
<app-created-time [createdTime]="item.createdTime"></app-created-time>

【讨论】:

  • 感谢您提供此解决方案,但我认为在 created-time.component.html 中应该是 &lt;span *ngIf="createTime; else notAvailable"&gt;
  • 这个解决方案适合 HTML 文本内容,但我也想在 HTML 属性上添加相同的日期格式到 [attr.title]="&lt;here&gt;" 我无法使用上述解决方案实现这一点。
  • @diEcho 我不清楚你想要什么。你能解释一下吗?
  • 只要有 Date 对象,它将以“中等”格式显示时间,否则不适用。这个答案不适合 [innerHTML]
  • 感谢&lt;ng-container&gt;的使用
猜你喜欢
  • 2012-05-01
  • 2014-10-30
  • 1970-01-01
  • 2021-11-03
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-23
相关资源
最近更新 更多