angular - 使用 @Input 装饰器访问传递的数据

标签 angular angular2-components

我有一个看起来像这样的子组件

子组件

@Component({
   selector: 'child-component',
   //TemplateUrl, Styles and Providers
})

export Class ChildComponent implements OnInit{
  @Input()
  arrayToGet; //An array that I want to pass from Parent to child

  ngOnInit(){
     console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
  }

  //A bunch of methods to work with the array I get
}

父组件

@Component({
   selector: 'parent-component',
   template: '<div>
                <child-component [arrayToGet]="models"></child-component>
              </div>',
   //A bunch of Styles and Providers
})

export class ParentComponent{
   models;

   constructor(......){}

   ngOnInit(){
      //Get an array from a service assign to this.models;
   }
}  

问题是我无法对 ChildComponent 内的 arrayToGet 执行任何操作。不过,我可以在 ChildComponent 的 HTML 中使用 arrayToGet 上的属性。

有什么想法吗?

最佳答案

每当尝试使用 @Input 装饰器将数据从 parent 传递到 child 时,并且传递数据在 时不可用child 初始化,最好使用 setter,而不是直接绑定(bind)到 child 组件中的变量。每当父组件中的数据更新时,使用 setter 将更新子组件 vairable。

export Class ChildComponent implements OnInit{
  arrayToGet; //An array that I want to pass from Parent to child

  ngOnInit(){
     console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
  }

  @Input('arrayToGet')
  set _arrayToGet(data: Array) {
     this.arrayToGet = data;
     console.log(this.arrayToGet);
  }

  //A bunch of methods to work with the array I get
}

关于angular - 使用 @Input 装饰器访问传递的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46138267/

相关文章:

javascript - 使用 Angular 表单取消提交

angular - ngIf 与 viewchild

javascript - 如何在父组件中调用子组件的函数

javascript - 用 jasmine 测试 Material Design Angular 组件

javascript - 在 MS Edge 中禁用表单完成

angular - Chrome 暂停请求 15 秒

angular - 如何降级用 angular2 编写的自定义管道以用于 angular 1.5?

angular - Employee类型中缺少属性toggleEdit”,但这是一种方法,该怎么办?Angular2

angular - 在 Angular 单个组件中导入第 3 方 javascript 库

Angular 2 - 模块在刷新时加载两次