Angular2 Novice Passing data from parent component to child

I am looking at a sample Angular 2 project and pasted some code to try to pull a value from a movie object that is passed to a nested child component.

In the parent code, I have the following:

<div class="col-sm-6 col-md-4 col-lg-3 col-xs-6" *ngFor="let movie of movies; let i = index;">
  <movie-card [movie]="movie"></movie-card>
</div>

In my movie-card.component.ts file, I have this code:

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

@Component({
  selector: 'movie-card',
  templateUrl: './movie-card.component.html',
  styleUrls: ['./movie-card.component.css']
})
export class MovieCardComponent {

  @Input()
  movie: Object;

  constructor() {

  console.log('movie : ' + this.movie);
  }

}

Output to my Chrome console:

20 movie : undefined  movie-card.component.ts:15 

But in movie-card.component.html

 {{movie.Name}}

html will display the name of the movie.

I want to send the movie.Name value to my service like this.

_anatomyService.getImage(this.movie.Name);

However, the meaning of the film is undefined. What? I do not understand?

Thanks in advance.

+4
source share
3 answers

You can use the set in your meaning

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

@Component({
  selector: 'movie-card',
  templateUrl: './movie-card.component.html',
  styleUrls: ['./movie-card.component.css']
})
export class MovieCardComponent {

  @Input()
  set movie(movie: Object){
   console.log(movie);
    //asign it to a value or do something with it
  }

}
+3
source

your movie-card.component.ts file should be like this.

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

    @Component({
      selector: 'movie-card',
      templateUrl: './movie-card.component.html',
      styleUrls: ['./movie-card.component.css']
    })
    export class MovieCardComponent {

      @Input()
      movie: Object;

      constructor() { }

    ngOnInit() {     <-- your this.movie should be in ngOnInit lifecycle hook
         console.log('movie : ' + this.movie);
       }

    }

http://learnangular2.com/lifecycle/

+2

There is no initialized input value in the constructor. You have to wait untilngOnInit()

ngOnInit() {
  console.log('movie : ' + this.movie);
}

See also more detailed angular2 lifecycle information here

+1
source

Source: https://habr.com/ru/post/1664031/


All Articles