2

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?

Siavash
  • 2,813
  • 4
  • 29
  • 42
xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • Just my Dumb Vue self asking this question but are Components not the right thing for your use case? – niclas_4 Oct 29 '18 at 06:35
  • there is one [article](https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02) which makes me more confuse which one to use as there are many such as decorator `viewChild`, `ViewContainerRef`, `Templateref`, `viewRef` – xkeshav Oct 29 '18 at 06:38

1 Answers1

2

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>
Dmitriy Snitko
  • 931
  • 5
  • 14