Home > database >  Hide div element after a few seconds Angular 7
Hide div element after a few seconds Angular 7

Time:07-19

So I am having trouble understanding how to do this and how to approach this issue... I have a scroll animation on my page and I want to hide that div with animation after 3 seconds when it comes into view.

My HTML code for animated element is:

<div >
  <div >
   <span></span>
   <span></span>
   <span></span>
  </div>
</div>

Code in my Typescript is:

hideAnimatedDiv() {
        const animatedDiv = document.getElementsByClassName('scroll-animation');
        this.animatedDiv = true;
        setTimeout(() => {
            console.log('hide');
            this.animatedDiv = false;
        }, 3000);
    }

I keep getting this error:

ERROR in src/app/configurator/configurator.component.ts(577,14): error TS2339: Property 'animatedDiv' does not exist on type 'ConfiguratorComponent'.
src/app/configurator/configurator.component.ts(580,18): error TS2339: Property 'animatedDiv' does not exist on type 'ConfiguratorComponent'.

CodePudding user response:

Your code is trying to find animatedDiv property as global, because you have used this.animatedDiv instead try like this.

HTML

<div >
  <div id="scroll-animation" >
    <span>a</span>
    <span>b</span>
    <span>c</span>
  </div>
</div>

TS

ngOnInit() {
   this.hideAnimatedDiv()
}

hideAnimatedDiv() {
   let animatedDiv = document.getElementById('scroll-animation');
   animatedDiv.style.display = 'block';
   setTimeout(() => {
     console.log('hide');
     animatedDiv.style.display = 'none';
   }, 3000);
}

To hide any element, we need to use style.display property of that element, like shown in the code.

Note: I have used ngOnInit function to make sure that div is hidden after component load only.

CodePudding user response:

If you want to hide div I would suggest you this:

<div >
  <div  *ngIf="isDisplayed">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

As you can see I added " *ngIf="isDisplayed" ". You should add the property "isDisplayed" to the component.

public isDisplayed: boolean = true;

hideAnimatedDiv() {
    setTimeout(() => {
        this.isDisplayed = false;
    }, 3000);
}

If you want to add animation in Angular, the best way is to implement it as Angular Team suggests:

With this specific case I would use ":enter" ":leave" approach: https://angular.io/guide/transition-and-triggers#use-of-ngif-and-ngfor-with-enter-and-leave

  • Related