首页 > 解决方案 > 从父级到子级的角度传递数据是未定义的

问题描述

我正在尝试使用组件交互将数据从父级传递给子级

在父组件中:

<app-news [leonardType]="countTitle"></app-news>

子组件

export class NewsComponent implements OnInit, AfterViewChecked {

  @Input() leonardType: string;
  title;
  constructor(
    public newsService: NewsService
  ) {}
  ngAfterViewChecked() {
    console.log(this.leonardType); ==> undefined
    console.log(this.newsService.leonardCategory[this.leonardType]); ==> undefined
  }

  ngOnInit() {
    this.title = this.newsService.leonardCategory[this.leonardType];
    console.log(this.leonardType); ==> undefined
    console.log(this.newsService.leonardCategory[this.leonardType]); ==> undefined
}

在子组件服务中,我有一个对象:

leonardCategory = {
  countTitle: "TITLE 1",
  indTitle: "TITLE 2"
};

我认为该视图尚未呈现,但要么ngAfterViewChecked我得到未定义的输出leonardType

标签: angulartypescript

解决方案


如果要传递countTitle文本,只需将其包装成''. 没有''它被认为是组件中的一个属性undefined,所以为什么要进入undefined子组件。

<app-news [leonardType]="'countTitle'"></app-news>

或者只是没有[]

<app-news leonardType="countTitle"></app-news>

推荐阅读