【问题标题】:Getting error in Passing multiple data from parent to child component in Angular在Angular中将多个数据从父组件传递到子组件时出错
【发布时间】:2018-09-20 10:40:28
【问题描述】:

我正在尝试将两个变量从父组件发送到子组件。为此,我已经在一个对象中初始化了这两个数据,您可以在下面看到

export class AppComponent {
  title = 'app';
  myObj = {
    FirstInputString : 'Hello I am coming from Parent',
    SecondInputString :  'I am second value coming from parent'
  };

我已将子选择器放置到父组件视图 .html 文件中,其中我使用 @input name myInput 将其绑定到对象名称。

<app-form-test [myInput]='myObj' (myOutput)="getData($event)"></app-form-test>

但是在子组件中,当我使用对象值时..我是 无法访问父对象中已定义对象的键值 对象

export class FormTestComponent implements OnInit {
  @Input() myInput: string;

  ngOnInit() {
    console.log(this.myInput.FirstInputString);
    console.log(this.myInput.SecondInputString);
  }
}

【问题讨论】:

  • 错误是什么?
  • 控制台没有显示错误,只有父组件的数据没有显示。
  • 我认为我无法正确绑定子模板中的对象
  • 我能够获取数据,您的代码只有一个问题 myInput: string;而不是这个,你应该有 myInput: any;
  • @KirkLarkin 这就是我的评论。代码没有问题。我收到了 console.log 语句。注意:编译编译时会报错

标签: angular angular-decorator


【解决方案1】:

应用组件

export class AppComponent {
  title = 'app';
  myObj = {
    FirstInputString : 'Hello I am coming from Parent',
    SecondInputString :  'I am second value coming from parent'
  };

应用组件 html

<app-form-test [myInput]="myObj" (myOutput)="getData($event)"></app-form-test>

表单测试组件

export class FormTestComponent implements OnInit {
  @Input() myInput: any;

  ngOnInit() {
    console.log(this.myInput.FirstInputString);
    console.log(this.myInput.SecondInputString);
  }
}

以上对我来说非常好。

注意:myInput: string 我将其更改为 myInput: any,但运行时不会导致任何错误。

请找到 stackblitz https://stackblitz.com/edit/angular-8skzfj?file=src%2Fapp%2Fheader%2Fheader.component.ts

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2017-06-25
    • 2021-01-15
    • 2017-12-24
    • 1970-01-01
    • 2022-01-19
    • 2018-04-16
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多