首页 > 解决方案 > 比较 HTML 文件中的 2 个字符串 - Angular

问题描述

我正在使用 angular 7,我想知道如何比较两个strings. 在这种情况下,我的每个strings模拟一个date,比如说“2019-12-26”和“2018-12-26”。

Javascript比较它们非常简单,因为我只需要使用运算符:

console.log(today > "2018-12-06");

它正在按我想象的那样工作。它基本上返回true。不过,我试图从我的 HTML 文件中做同样的事情

 <div *ngIf="today > example.endDate">

beingtoday和 'example.endDate' 两个包含与我在示例中使用的strings完全相同的内容,但它没有显示它们中的任何一个。stringsJavascript

有没有其他方法可以进行这种比较?

问候,马里奥

更新 我再次查看了这个问题,似乎比较不是问题,但获取变量的方式是。

我得到一个变量ngOnInit()

 ngOnInit() {

    this.getCurrentDate();
  }

  //Get current date
  getCurrentDate() {
    let aux = new Date();
    //2 characteres
    let dd = String(aux.getDate()).padStart(2, "0");
    let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
    let yyyy = aux.getFullYear();
    let today = yyyy + "-" + mm + "-" + dd;
    let other = "2019-01-31";
  }

问题是我直接在我HTML之前展示的方式中使用了这个变量。我得到的错误如下:

ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'ngIf:未定义'。当前值:'ngIf: true'。

所以问题是我HTML在获取value. 或者至少这是我所理解的

为了检查这个错误,我创建了一个Stackblitz表示。在它上面,我创建了两个例子:

  1. 未开启的变量ngOnInit()
  2. 中的变量ngOnInit()

https://stackblitz.com/edit/angular-jjgsmq?file=src%2Fapp%2Fhello.component.ts

标签: htmlangulardate

解决方案


最简单的解决方案就是并且您确定 ngOnInit 是适合您的 LifeCycle 挂钩吗?如果组件“重”以呈现其他明智的 ngAfterViewInit() 将是我的选择,我会尝试 ngAfterContentInit()

<div *ngIf="IsTodayBigger()">

    ngOnInit() {
    this.getCurrentDate();
  }

 IsTodayBigger(): boolean {
    today=this.getCurrentDate()
    exampleEndDate= example.endDate;//use binding or ViewChild if needed
  return today&&exampleEndDate&& today> example.endDate
  }

  //Get current date
  getCurrentDate() {
    let aux = new Date();
    //2 characteres
    let dd = String(aux.getDate()).padStart(2, "0");
    let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
    let yyyy = aux.getFullYear();
    today = yyyy + "-" + mm + "-" + dd;
    let other = "2019-01-31";
  }

推荐阅读