【问题标题】:*ngIf-else not showing else results*ngIf-else 不显示 else 结果
【发布时间】:2019-02-13 18:29:03
【问题描述】:

我不知道为什么这不起作用并且我被卡住了。谁能发现我的代码有什么问题?

当没有票可显示时,我试图显示 Not found 消息。我尝试通过门票数组长度获取结果,但它总是显示长度为0。

HTML

<ng-container *ngIf="tickets; else elseTemplate">
  <div class="container">
    <div class="row justify-content-md-center">
      <div class="col-sm-4" *ngFor="let ticket of tickets">
        <div class="card">
          <h5 class="card-header"><span class="fa fa-ticket"></span> Pileti nr. {{ticket._id}}</h5>
        </div>
      </div>
    </div>
  </div>
</ng-container>
<ng-template #elseTemplate>
  <div><h1>Ticket not found.</h1></div>
</ng-template>

TS

import { Component, OnInit } from '@angular/core';
import { TicketService } from '../../ticket.service';
import { ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import {Location} from '@angular/common';

@Component({
  selector: 'app-reg-ticket-list',
  templateUrl: './reg-ticket-list.component.html',
  styleUrls: ['./reg-ticket-list.component.css']
})
export class RegTicketListComponent implements OnInit {

  reg: string;

  public tickets = [];

  constructor(private ticketService: TicketService, private route: ActivatedRoute, private _location: Location) { }

  ngOnInit() {
      this.reg = this.route.snapshot.params.reg;
      this.ticketService.getTicketsByReg(this.reg)
          .subscribe(data => this.tickets = data);
    }

    dateFormat(date) {
      moment.locale('et');
      return moment(date).format("Do MMMM YYYY HH:mm:ss")
    }

    goBack() {
      this._location.back();
    }

}

【问题讨论】:

  • *ngIf="tickets; 只会检查它是否为空。试试*ngIf="tickets &amp;&amp; ticket.length;
  • 哦!我不知道。现在可以用了,谢谢!如果您想将其添加为答案,我会接受它:)

标签: node.js angular mongodb mongoose angular6


【解决方案1】:

当使用*ngIf="tickets; 时,这只会检查tickets 是否为假,空数组是否为假(尽管null 是)。

相反,您可以使用*ngIf="tickets &amp;&amp; ticket.length;,它还会检查长度是否不为0

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2022-08-18
    • 2017-11-24
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多