简体   繁体   English

ngFor不会在NavigationEnd事件Angular 6+上加载动态填充的数组

[英]ngFor does not load the dynamically populated array on NavigationEnd event Angular 6+

Having problem displaying array with ngFor on NavigationEnd Event, in the constructor of my class 在我的类的构造函数中,在NavigationEnd事件上使用ngFor显示数组出现问题

testArray = [];

constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    this.router.events.forEach(event => {
        if (event instanceof NavigationEnd) {
            this.testArray = [1, 2, 3,4];
        }
    });
}


<ol class="breadcrumb">
    <li *ngFor="let element of testArray"
        class="breadcrumb-item">
        {{element}}
    </li>
</ol>

Even though the array is populated when the NavigationEnd event happens, it does not display the contents of the array. 即使在NavigationEnd事件发生时填充了数组,它也不会显示数组的内容。 The html page does not seem to reload with new Array data. html页面似乎没有重新加载新的Array数据。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks 谢谢

Use setTimeout while setting the value. 设置值时使用setTimeout

   testArray = [];
       constructor(private activatedRoute: ActivatedRoute,
              private router: Router) {
    this.router.events.forEach(event => {
      if (event instanceof NavigationEnd) {
        setTimeout(()=>{
           this.testArray = [1, 2, 3,4];
        });

      }
    });
  }

Is better if you use async pipe here 如果在这里使用异步管道会更好

testArray: Observable<number[]>;

constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    testArray = this.router.events.pipe(filter(event) => event instanceof NavigationEnd).map(() => [1, 2, 3,4])
}

<ol class="breadcrumb">
    <li *ngFor="let element of testArray | async" class="breadcrumb-item">
        {{element}}
    </li>
</ol>

The view seems to be loaded before the array population. 该视图似乎在数组填充之前加载。 You can try to make your class implement "OnInit" available from "@angular/core" and make the foreach on "ngOnInit" method : 您可以尝试使您的类实现“ @ angular / core”中的“ OnInit”,并使foreach成为“ ngOnInit”方法:

ngOnInit() {
    this.router.events.forEach(event => {
      if (event instanceof NavigationEnd) {
        this.testArray = [1, 2, 3,4];
      }
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM