最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ngAfterViewInit is not working or am I doing something wrong - Stack Overflow

programmeradmin4浏览0评论

My ngAfterViewInit function is not working as expected. I have feeling that I am missing something here.

  ngOnInit() {
   this.dataService.getUsers().subscribe((users) => {this.users = users) ;  
  }

  ngAfterViewInit() {
    if (document.getElementById('target')) {
        document.getElementById('target').scrollIntoView({
          behavior: 'auto',
          block: 'center',
          inline: 'center',
       });
   }

So basically, I'm using ngAfterViewInint() function to scroll to the current item, after the view complete loaded. Inside ngOnInit(), if I am not calling subscribe() and just put a variable there. It works just fine. But its not the case that what i am asking.

I have a work around by using setTimeOut() inside ngAfterViewInit(). But I don't like it. I dont like the fact that its relies on timeout. And I think there would be a better solution for it. Any ideal ? Thanks all.

My ngAfterViewInit function is not working as expected. I have feeling that I am missing something here.

  ngOnInit() {
   this.dataService.getUsers().subscribe((users) => {this.users = users) ;  
  }

  ngAfterViewInit() {
    if (document.getElementById('target')) {
        document.getElementById('target').scrollIntoView({
          behavior: 'auto',
          block: 'center',
          inline: 'center',
       });
   }

So basically, I'm using ngAfterViewInint() function to scroll to the current item, after the view complete loaded. Inside ngOnInit(), if I am not calling subscribe() and just put a variable there. It works just fine. But its not the case that what i am asking.

I have a work around by using setTimeOut() inside ngAfterViewInit(). But I don't like it. I dont like the fact that its relies on timeout. And I think there would be a better solution for it. Any ideal ? Thanks all.

Share Improve this question edited Dec 18, 2019 at 22:29 Muhammed Albarmavi 24.4k9 gold badges71 silver badges92 bronze badges asked Dec 17, 2019 at 22:22 daniel8xdaniel8x 1,0804 gold badges20 silver badges38 bronze badges 5
  • Does your target element depend on data returning from your request? – Pytth Commented Dec 17, 2019 at 22:25
  • 1 You cannot refer to elements like this in angular 2+ Refer to this on calling child native elements stackoverflow.com/questions/48226868/… – Rager Commented Dec 17, 2019 at 22:26
  • @Pyth yes. it is. – daniel8x Commented Dec 17, 2019 at 22:26
  • @Rager Thanks. let me try. – daniel8x Commented Dec 17, 2019 at 22:36
发布评论

评论列表(0)

  1. 暂无评论