I have a parent component with a component inside
@Component({
selector: 'report',
template: `
<div *ngFor="let report of reports">
{{ report }}
<tags-ui [tags]="tagsData"></tags-ui>
</div>
`,
styles: []
})
export class HelloComponent {
reports = [];
counter = 0;
tagsData: Tag[] = [{
id: 1,
name: 'Bishkaan'
}, {
id: 2,
name: 'Pakistan'
}, {
id: 3,
name: 'Malta'
}];
cronHandle = setInterval(() => {
this.counter++;
if (this.counter % 2 === 0) {
this.reports = ['TURNIP', 'RADISH', 'BEANS'];
} else {
this.reports = ['1', '2', '3'];
}
}, 3000);
}
The child component is defined as follows
@Component({
selector: 'tags-ui',
template: `
<div #tagsWrapper>
<div *ngFor="let tag of tags">
<span>{{ tag.name }}</span>
</div>
</div>
`,
styles: []
})
export class TagsUiComponent implements AfterViewInit {
@ViewChild('tagsWrapper') tagsWrapperRef: ElementRef;
@Input() tags: Array<Tag>;
public ngAfterViewInit() {
console.log('hmmm inside tags ui');
console.log(`height of tags ui: ${ this.tagsWrapperRef.nativeElement.offsetHeight }`);
}
}
Now, if i make the viewport small enough vertically so that the scrollbar appears and then scroll all the way to the bottom, it jumps back to the top after the next execution of the callback defined in setInterval(). And now the interesting part, the scrolling to top stops just by commenting out or removing the second console.log() i-e
console.log(`height of tags ui: ${ this.tagsWrapperRef.nativeElement.offsetHeight }`);
from the tags-ui component's ngAfterViewInit(). You can try it out here: https://stackblitz.com/edit/angular-ivy-dkujkq.
What is so special about calling a DOM api on an element in a child component that makes the whole page to scroll up ?