创建可在各个页面上使用的可重用模板 [英] Create a reusable template which can be used on various pages

查看:89
本文介绍了创建可在各个页面上使用的可重用模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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 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>

In my angular 5 application, I need to do this on every HTML page

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

and on the end of page create that template

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

there is repeating the same line of code on every HTML page, so looking for any solution which helps me to create one common component/directive which has only #notAvailable content and can be used on every page with *ngIf?

earlier in angularJS, we can create a separate template file and will be used but in new angular, there is no HTML can be attached in the directive, so a bit confused how to do this?

someone, Please guide me how to achieve this and what need to write in the respective component and HTML?

解决方案

You can create a component ex.: 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>

这篇关于创建可在各个页面上使用的可重用模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆