ngx-bootstrap accordion open panel dynamically

4.9k views Asked by At

I use ngx-bootstrap accordion to show a list of blog posts.

Here is the template:

<accordion id="blog-list">
    <accordion-group *ngFor="let post of posts; let first = first;" [isOpen]="first" id="post-{{post.id}}">
        <!-- Here goes content irrelevant to the question -->
    </accordion-group>
</accordion>

I also use some global config, to have only one open accordion panel at a time.

export function getAccordionConfig(): AccordionConfig {
  return Object.assign(new AccordionConfig(), { closeOthers: true });
}

Now, when a post gets updated, I update it in the list, like so:

constructor(private elementRef: ElementRef, private postService: PostService) {
    this.postService.updatedPost.subscribe(val => {
      let i = this.posts.findIndex(post => post.id === val.id);
      this.posts[i] = val;
      let element = elementRef.nativeElement.querySelector('#post-' + val.id);
      element.setAttribute('isOpen', true); // <- this does not work
      element.scrollIntoView(true);
    });
  }

Updating and scrolling works fine, but I can't figure out how to get the panel to open. After the view gets updated and scrolled all panels are closed. I want the panel with the updated post to be open.

1

There are 1 answers

1
valorkin On BEST ANSWER

So issue is in [isOpen]="first", first post will be opened by default direct manipulation with DOM will no trigger bindings updates

what you could do is:

[isOpen]="activPostIndex === index"

activPostIndex = 0;
constructor(private elementRef: ElementRef, private postService: PostService) {
    this.postService.updatedPost.subscribe(val => {
      this.activPostIndex = this.posts.findIndex(post => post.id === val.id);
      this.posts[i] = val;
    });
  }