0

This component:

export class ChildComponent {
  @Input()
  child: Child;

  mychild: Child = { 
    id: this.child.id,
    name: this.child.name: 
  };
}

returns this error:

TypeError: undefined is not an object (evaluating 'this.child.id')

Aren't the properties of the @Input target object automatically available within the component?

1 Answer 1

3

mychild property is assigned in component constructor. The bindings aren't available at this point.

Lifecycle hooks exist to make this possible. According to the reference,

ngOnInit

Initialize the directive/component after Angular initializes the data-bound input properties.

ngOnChanges

Respond after Angular sets a data-bound input property. The method receives a changes object of current and previous values.

And the order of execution is

ngOnChanges

before ngOnInit and when a data-bound input property value changes.

ngOnInit

after the first ngOnChanges.

So it should be

export class ChildComponent implements OnInit {
  @Input()
  child: Child;

  mychild: Child;

  ngOnInit() {
    this.mychild = { 
      id: this.child.id,
      name: this.child.name: 
    };
  }
}

if child input isn't supposed to be changed after initialization, otherwise ngOnChanges hook should be used.

The code above seems to be redundant, because this.child is already available after initialization and can be used directly instead of this.mychild.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.