Passing a value from parent to child. The value that is received in the child component is undefined.
Here is my app.component with a working example
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface ItemsResponse {
data: any[];
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit() {
this.getPosts();
console.log(this.name); // name is undefined
}
name;
results:Array<any> = []; // code changed
getPosts() {
this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3')
.subscribe(res => this.name = res); // code changed
}
}
Here is my hello.component with a working example, where the data is passed to the child component.
As you can see the name that is passed from parent to child component through Angular's @Input
decorator is undefined in the constructor.
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<pre>{{name | json}}</pre>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
}
and in the hello.component
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1>hi</h1><pre>{{name | json}}</pre>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
ngOnInit() {
console.log('name', this.name); // name is undefined
}
@Input() name: string;
}