我使用ngx-bootstrap手风琴来显示博客文章列表。
以下是模板:
<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>
我也使用一些全局配置,一次只有一个开放的手风琴面板。
export function getAccordionConfig(): AccordionConfig {
return Object.assign(new AccordionConfig(), { closeOthers: true });
}
现在,当帖子更新时,我会在列表中更新它,如下所示:
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);
});
}
更新和滚动工作正常,但我无法弄清楚如何让面板打开。视图更新并滚动后,所有面板都关闭。我希望带有更新帖子的面板打开。
答案 0 :(得分:1)
问题出在[isOpen]="first"
,默认情况下会打开第一篇文章
使用DOM直接操作不会触发绑定更新
你能做的是:
[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;
});
}