首页 > 解决方案 > Angular 6 @Viewchild 不适用于延迟加载

问题描述

这是我的代码,它给出了错误无法读取未定义的属性标题。

父组件

import { Child } from './child.component';
@Component({
  selector: 'parent',
})
export class ParentComponet implements OnInit, AfterViewInit {
 constructor(){}

  @ViewChild(Child) child: Child;

  ngAfterViewInit(){
    console.log("check data", this.child.title)
  }
}

而子组件是。

@Component({
      selector: 'child',
    })
    export class ChildComponet {

     public title = "hi"
     constructor(){}

    }

routing.module.ts 就像

{
        path: "",
        component: ParentComponent,
        children: [
            {
                path: '/child',
                component: ChildComponent
            }
        ]
}

并给出错误是

ERROR TypeError: Cannot read property 'title' of undefined(…)

标签: javascriptangularangular6lazy-loading

解决方案


我认为您缺少与创建组件相关的“模板”或“模板网址”

父组件

import { ChildComponent } from './child.component';    // {ChildComponent} not {Child} as we are referencing it to the exported class of ChildComponent

@Component({
   selector: 'parent',
   template: `<child></child>`
})
export class ParentComponet implements OnInit, AfterViewInit {...}

子组件

@Component({
  selector: 'child',
  template: `<h1>{{ title }}</h1>`
})
export class ChildComponent {...}       // Be sure to spell it right as yours were ChildComponet - missing 'n'

根据用户对此线程的说明进行更新

已添加Stackblitz Demo供您参考(检查控制台)

如果您想访问在父组件下呈现的 ChildComponent,<router-outlet>您可以利用router-outlet 的(激活)支持的属性来实现

每当实例化新组件时,路由器出口都会发出激活事件

角度文档

ParentComponent 的模板

@Component({
   selector: 'parent',
   template: `<router-outlet (activate)="onActivate($event)"></router-outlet>`
})
export class ParentComponent {

    onActivate(event): void {
        console.log(event);         // Sample Output when you visit ChildComponent url
                                    // ChildComponent {title: "hi"}

        console.log(event.title);   // 'hi' 
    }

}

结果将根据您父母的孩子下访问的页面而有所不同

如果你访问Child1Component你会得到它的实例Child1Component {title: "hi"}

如果你访问Child2Component你会得到它的实例Child2Component {name: "Angular"}

然后这些结果将反映在您 ParentComponent 的 onActivate(event) 控制台上,供您访问


推荐阅读