tyrion
tyrion

Reputation: 742

Angular2: Passing data to child components

I have a simple app where there is a main component and a child component. The main component accepts a data value which would be used by the child component. so I define like this in index.html -

  <my-app [mydata]="'Some sample data'">
    loading...
  </my-app>

And in my main component, I define the input property 'mydata' -

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <child-app [data]="mydata"></child-app>
    </div>
  `,
  directives: [childApp],
  inputs: ['mydata']
})
export class App {
  mydata: string;

  constructor() {
    this.name = 'Angular2'
  }
}

In the main component's view I have used the child component and passed the mydata property and bind it to the 'data' property of the child component -

  <child-app [data]="mydata"></child-app>

And here is my child component -

@Component({
  selector: 'child-app',
  providers: [],
  template: `
    <div>
      <h2>This is my data: {{data}}</h2>
    </div>
  `,
  directives: [childApp],
  inputs: ['data']
})
export class childApp {
  data: string;

  constructor() {
    this.name = 'Angular2'
  }
}

Unfortunately, the final output doesn't show the 'Some sample data' which I passed in the index.html.

See this plunk for sample code.

Any suggestion on how to pass the data across child component?

Upvotes: 3

Views: 1403

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657048

@Input() is currently not supported on the root component (AppComponent).

See also https://github.com/angular/angular/issues/1858

As a workaround you can use

constructor(ref:ElementRef) {
  ref.nativeElement.getAttribute('mydata');
}


<my-app mydata="Some sample data">
  loading...
</my-app>

(allows only String)

Upvotes: 2

Related Questions