Σάββατο 16 Μαΐου 2020

Conditional HTML display with ngTemplate








Show/hide HTML with ngTemplate


If no elements are retrieved, show "No Data"message.

To simulate this, click on Toggle to update a 'noData' flag

Clicking on Toggle simulates no-data case:





1. Component - HTML


<button mat-button (click)="toggleDisplay()"> Toggle </button>
<div *ngIf="this.noData; then noDataMessage else mainDisplay"></div>
<ng-template #mainDisplay>
    <br/><br/>
    <p>All cars:</p>
    <br/>
    <div *ngFor="let car of cars">
        {{car.name}} - {{car.brand}} - {{car.type}}
    </div>
</ng-template>
<ng-template #noDataMessage>
    <br/><br/>
    <div>
    No data available
    </div>
</ng-template>




2. Component - TS


import {Component, OnInit} from '@angular/core';

interface ICar {
  name: string,
  brand: string,
  type: string
}
@Component({
  selector: 'jhi-test-comp',
  templateUrl: './test-comp.component.html',
  styleUrls: ['./test-comp.component.scss']
})
export class TestCompComponent implements OnInit {
  noData = false;
  cars: ICar[] = [{name: 'i10', brand: 'Hyundai', type: 'gasoline'}, {name: 'swift', brand: 'Suzuki', type: 'gasoline'}, {name: 'Y', brand: 'Tesla', type: 'electric'}];
  constructor() {
  }
  ngOnInit(): void {
  }
  toggleDisplay(): void {
    this.noData = !this.noData;
  }
}



3. Component - CSS

.mat-button {
  border-radius: 30px;
  font-size: 2.08vh;
  background-color: #3339ea;
  color: white;
  width: 10%;
}


Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?