【问题标题】:Angular passing data from parent to child is undefined从父级到子级的角度传递数据是未定义的
【发布时间】:2018-07-31 09:21:59
【问题描述】:

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

在父组件中:

<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 的未定义输出

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    如果您想传递countTitle 文本,只需将其包装成''。没有'',它被认为是undefined组件中的一个属性,所以为什么你在子组件中得到undefined

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

    或者只是没有[]

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

    【讨论】:

    • 输入类型为字符串。 @Input() leonardType: 字符串;
    • 我传递的只是文字,有可能吗?
    • @SurenSrapyan leonardTypestring :|
    • @infodev 对不起。您需要将文本countTitle 传递给孩子,因此将其包含在'' 中。更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多