Ole
Ole

Reputation: 46900

Showing and hiding the angular material toolbar on an interval?

I'm attempting to test the CSS animation for showing and hiding the angular material toolbar in this demo.

Within the app component the hide property is switched on an interval like this:

  hide:boolean = false
  show() {
    this.hide = !this.hide;
    console.log(`Hide? ${this.hide}`)
  }
  constructor() {
    this.show.bind(this)
    setInterval(this.show, 2000)
  }

The CSS is declared like this on the mat-toolbar:

<mat-toolbar [ngClass]="hide ? 'hideToolbar' : 'showToolbar'"
             class="hideShowToolbar"><h2>Material Baseline</h2>
</mat-toolbar>

The ngClass directive does not toggl between hideToolbar and showToolbar. Thoughts?

Also tried an Observable variation:

Stackblitz

Upvotes: 1

Views: 2994

Answers (2)

coder
coder

Reputation: 8702

May be here you will able to use rxjs library interval like below in ngOnInit lifecycle hook:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  hide:boolean = false
  secondsCounter = interval(2000);
  show() {
    this.hide = !this.hide;
    console.log(`Hide? ${this.hide}`)
  }

  ngOnInit() {
    this.secondsCounter.subscribe(()=>{
      this.show();
    })
  }
}

Working DEMO

In above code we're subscribing to empty response by rxjs observable in ngOnInit(). Reactivex/Rxjs is really useful when it comes to perform actions reactively and it has been one of the main focus of angular developer team at google to attract community towards its powers.

Useful sources to know more about rxjs : https://angular.io/guide/rx-library https://www.youtube.com/watch?v=aYurQaN3RoE (very intuitive talk/must watch)

Upvotes: 1

ForrestLyman
ForrestLyman

Reputation: 1652

I would do it like this:

export class DemoComponent implements OnInit{
  public hidden: boolean;

  ngOnInit() {
    setInterval(() => {
      this.hidden = ! this.hidden;
    }, 2000);
  }
}

The toggle a hidden class in the template:

<mat-toolbar [class.hidden]="hidden" class="hideShowToolbar">
<h2>Material Baseline</h2>
</mat-toolbar>

Here is a sample transition that will animate the toolbar in from the right:

mat-toolbar{
  position: fixed;
  top:10px;
  right: 10px;
  width: 420px;
  transition:right .25s linear;
  &.hidden{
    right: -420px;
  }
}

Upvotes: 2

Related Questions