Tengo un componente principal con un componente dentro
@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); }El componente hijo se define de la siguiente manera
@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 }`); } }Ahora, si hago que la ventana gráfica sea lo suficientemente pequeña verticalmente para que aparezca la barra de desplazamiento y luego me desplazo hasta el final, vuelve a la parte superior después de la siguiente ejecución de la devolución de llamada definida en setInterval(). Y ahora la parte interesante, el desplazamiento hacia arriba se detiene simplemente comentando o eliminando el segundo console.log(), es decir
console.log(`height of tags ui: ${ this.tagsWrapperRef.nativeElement.offsetHeight }`);de ngAfterViewInit() del componente tags-ui. Puedes probarlo aquí: https://stackblitz.com/edit/angular-ivy-dkujkq .
¿Qué tiene de especial llamar a una API DOM en un elemento de un componente secundario que hace que toda la página se desplace hacia arriba?