chris01 chris01 - 3 years ago 243
TypeScript Question

Angular2: Visibility of Input-properties

I have a component parent that calls another component child with an input-property.

The property is available in the childs template but not in the constructor or OnInit. Thats normal behaviour or am I doing something wrong?

parent.component.ts

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

@Component({
selector: "parent",
template: `<child [name]="'foobar'"></child>`
})

export class ParentComponent
{
}


child.component.ts

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

@Component({
selector: "child",
template: "name={{ name }}"
})

export class ChildComponent
{
@Input () name:string="init";

constructor ()
{
console.log ("constr: " + name);
}

ngOnInit ()
{
console.log ("oninit: " + name);
}
}


EDIT


  • Corrected my sample and put @Input inside the class.

  • Changed my sample to real code.
    The template shows "foobar", the console shows an empty string.


Answer Source

Change

console.log ("oninit: " + name);

to

console.log ("oninit: " + this.name);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download