简体   繁体   中英

Angular add class from component

I have this code which allow me to scroll in specific DIV, what I try to do is to add temporary class into that div when it's scrolled and remove the class let say after one second.

scrollTo (id) {
    setTimeout(() => {
      var titleELe = document.getElementById(id); // my destination div on scroll
      this.scrollMeElement.scrollToPoint(0, titleELe.offsetTop, 1000); // add class to it for 1 second
    }, 100);
};

How to do that?

Update

I have made this changes:

component

scrolledItem: boolean = false; // added

constructor(...){...}

scrollTo (id) {
    setTimeout(() => {
      var titleELe = document.getElementById(id);
      this.scrolledItem = true; // added
      this.scrollMeElement.scrollToPoint(0, titleELe.offsetTop, 1000);
    }, 100);
    this.scrolledItem = false; // added
};

Then in my html I've add [class.active] = "scrolledItem" like

<div id="{{message.id}}" [class.active] = "scrolledItem" class="receiver"></div>

This does add class to my div but there is 2 issues:

  1. It add class to all rows not only destination div.
  2. It doesn't remove active class from my div.

screenshot

一

Any idea?

You can try this code:

// Div to scroll
<div class="component-placehoder" #componentPlacehoder></div>

// create view child
 @ViewChild('componentPlacehoder', { static: true })
    componentPlacehoder: ElementRef;

// scroll to div  
this.componentPlacehoder.nativeElement.scrollIntoView(true, { block: 'end', behavior: 'smooth' });

In my opinion, you should use template variable item to pass into function scroll.

<div class="message" *ngFor="let message of listMessage" (click)="scroll(item)" #item>
  <span>Message {{ message }}</span>
</div>

So in your function you can access offsetTop , classList of HTMLElement in order to scroll and manipulate class.

scroll(item: HTMLElement) {
    window.scrollTo(0, item.offsetTop)
    if (this.oldElemt) {
      this.oldElemt.classList.remove('active')
    }
    item.classList.add('active')
    this.oldElemt = item
  }

Using a variable to save old element like oldElemt .

This is link demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM