Home > other >  Angular: Use Pipe Date with Format
Angular: Use Pipe Date with Format

Time:06-03

I have an elevator component. Whenever the elevator reaches the first floor, store the date and display it in dd/MM/yy format.

if floor === 1 show Date
else
return(empty)

The function I was trying to run is GetDate

My stackblitz : https://stackblitz.com/edit/angular-ivy-zbrapb?file=src/app/app.component.ts

CodePudding user response:

import { Component, OnInit } from '@angular/core';
import { interval, Observable, map, tap } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  floor$!: Observable<Number>;
  myDate: Date;

  ngOnInit(): void {
    this.floor$ = this.getNumbersInfinite();
  }

  getNumbersInfinite() {
    return interval(1000).pipe(
      map(() => Math.floor(Math.random() * 3)   1),
      tap(() => (this.myDate = new Date()))
    );
  }
}
<div *ngIf="floor$ | async as floor">
  {{ floor | replaceWordLoby }}
  <div *ngIf="floor == 1">
    {{ myDate | date: 'dd/MM/yy' }}
  </div>
</div>

CodePudding user response:

You try to get a number out of an Observable. That will not work. I've added a new var and a tap for a side effect. That will work. There are other ways to achieve this; create a Subject that will receive a next(true/false) based on the floor number and use ngIF to display the date.

export class AppComponent implements OnInit {
  floor!: Observable<Number>;
  floorNumber: number = -1;
  myDate = new Date();

  ngOnInit(): void {
    this.floor = this.getNumbersInfinite();
  }

  getNumbersInfinite() {
    return interval(1000)
    .pipe(
      map(() => Math.floor(Math.random() * 3)   1),
      tap(res =>this.floorNumber=res));
  }

  GetDate() {
    if (Number(this.floorNumber) === 1) {
      return true;
    }
    return false;
  }
}
  • Related