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

2024-01-15

在我的 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 中编写什么?


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

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

创建时间.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建可在各种页面上使用的可重用模板 的相关文章

随机推荐