0

I am new in angular4

I have an Registration process which contains multiple steps, So I am just hide/showing my steps of the basis of some conditions. So, Registration process contains parent and child component("sidebar" that show the value that user filled in last step).

I am passing a array from parent to child. And in each step I am updating my array with some values. When I'm printing my array in child HTML its working fine but when I trying to console the same array in child compenent.ts its showing nothing. I have to do some calculation like in my arary I have date of birth so I want to calculate the actual age of user and show the same on sidebar.

This is my array: MyArray This is how I am passing my array

Parent.html

<app child [MyArray]="MyArray"></app child>

ChildComponent.ts

import { Component, OnInit,Output,Input } from '@angular/core';
export class SidebarComponent implements OnInit {
     @Input() MyArray: string;

     ngOnInit() {
     console.log(this.MyArray,'ssss');     
}
}

If I use MyArray.email in my child.html then Its showing the value fine.

Anyone having any Idea What I am doing wrong here

2
  • I wonder how it works when you put Myarray.email where MyArray is a string Commented Feb 17, 2018 at 9:46
  • You can omit ":string" if you want. You don't have to declare it. Or you can declare as array as well. Commented Feb 17, 2018 at 9:49

1 Answer 1

3

If you are passing an array from your parent component to child, your input must be declared as array in your child component , if you really not sure about the type , you can put it as any

  @Input() MyArray: Array<any>;

and you can access the particular property using the index or using ngFor in the template

console.log(this.MyArray[0].email);

if you need to watch for the changes on array, you can use ngOnChanges

Respond when Angular (re)sets data-bound input properties...Called before ngOnInit() and whenever one or more data-bound input properties change.

ngOnChanges(changes) {
    // code here
}
Sign up to request clarification or add additional context in comments.

9 Comments

ok, but my question is at any point if my array is update then how can I get the array value in child component. Right now I am able to get the value in child HTML but not in component
Inside ngOnInit() I am consoling the array, But its showing nothing.
it should be available in the component as well. can you produce a demo
ngOnInit gets called only when the component gets called, so if you are looking for updated value it wont be there
Yes, That is my question how can I get the update value everytime?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.