创建可在各种页面上使用的可重用模板

Create a reusable template which can be used on various pages

在我的 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 页面上都重复了同一行代码,因此寻找可以帮助我创建一个通用 component/directive 的解决方案,它只有 #notAvailable 内容并且可以用于每页 *ngIf?

早期在angularJS中,我们可以创建一个单独的模板文件来使用,但是在新的angular中,没有HTML可以附加在指令中,所以有点困惑该怎么做?

哪位高手,请指导我如何实现这个,需要在各自的组件中写些什么,HTML?

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

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

创建-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>

一些-other.component.html

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