ngAfterViewInit局部变量未定义角度6

时间:2018-08-25 08:15:07

标签: angular6

我得到this.objectsCount is undefined in addcomponent function 我究竟做错了什么?如果我进行调试,则只有“ div,el,sidenav,subscription”。

export class SidenavComponent implements OnInit {
subscription: Subscription;
tog: { compact: boolean, tag: string };
objectsCount: { tag: any, ctrl: Object }[];
compact: boolean;
tag: string;
@ViewChild('sidebar') div;
objects: any;
constructor(private sidenav: SidenavService, private el: ElementRef) {
}
ngOnInit() {
  this.subscription = this.sidenav.onToggle().subscribe((toggle) => {
this.tog = toggle;
if (toggle.tag) {
  let nav = this.el.nativeElement;

  //nav.attributes.
 }
});
}
addcomponent(elem) {
 this.objectsCount.push({ tag: elem.nativeElement("tag").value, ctrl: 
 elem.nativeElement });
 }
 ngAfterViewInit() {
   this.addcomponent(this.div);

  }

}

1 个答案:

答案 0 :(得分:0)

您永远不会初始化objectsCount数组,请在OnInit函数中进行设置

  this.objectsCount = [];