Доступ к данным, переданным с помощью декоратора @Input

У меня есть дочерний компонент, который выглядит следующим образом

Дочерний компонент

@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;
   }
}  

Проблема в том, что я не могу выполнять какие-либо операции на arrayToGet внутри моего ChildComponent, Однако я могу использовать свойства на arrayToGet внутри моего ChildComponentHTML.

Какие-нибудь мысли?

2 ответа

Решение

Всякий раз, когда пытается передать данные из parent в child с помощью @Input декоратор и передаваемые данные недоступны на момент child инициализация, лучше использовать setterвместо привязки непосредственно к переменной в child составная часть. С помощью setter будет обновлять дочерний компонент, когда данные обновляются в родительском компоненте.

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
}

Попробуй это:

parent.component.html

<child-component [arrayToGet]="models"></child-component>

parent.component.ts

export class ParentComponent {
  private models: Array<any> = ["hello", "world"];
}

child.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'child-component',
    templateUrl: './child.component.html'
})

export class ChildComponent implements OnInit {

    @Input() arrayToGet;

    ngOnInit() {
        console.log('arrayToGet', this.arrayToGet);
    }
}
Другие вопросы по тегам