Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: how to pass attributes to child component?

In my application I have Home as root component and another generic component named as list which i'm rendering inside Home.

I want to pass data as property to my list component which is coming from XMLHttpRequest.

home.ts

import {Component} from 'angular2/core';
import {DashboardService} from '../../services/dashboard';
import {List} from '../contact/list';

@Component({
  selector: 'home',
  template: 
     `
     <h3>Home</h3>
     <List type="{{type}}"></List>
     `
  providers: [DashboardService],
  directives: [List],
})
export class Home {

  private _type: any;

  constructor(private _dashboardService: DashboardService) {
    this._dashboardService.typeToDisplay()
      .subscribe((type) => {
          this._type = type;
      });
  }
}

List.ts

@Component({
  selector: 'List',
  properties: ['type'],
  template: `
        <h2>list</h3>
  `,
  providers: [DashboardService]
})
export class List {

  private type: any;

  constructor(@Attribute('type') type:string) {
    this.type = type;
    console.log(type);
  }
}

I'm getting string data from typeToDisplay() method its an Http request & assigning to type variable. but when I passed as property to list component I'm getting null in List constructor.

I tried too but i'm getting "type" string same way.

Hope my question is Clear.

like image 350
Hitesh Balar Avatar asked Jan 21 '16 06:01

Hitesh Balar


1 Answers

This syntax

<List type="{{type}}"></List>

is setting a property not an attribute.
To set an attribute use either

<List attr.type="{{type}}"></List>

or

<List [attr.type]="type"></List>

If you just want to have the value available in List use

@Input() type: any;

instead of the attribute injection.
This way the value is not availabe yet inside the constructor, only in ngOnInit() or later.

like image 60
Günter Zöchbauer Avatar answered Sep 22 '22 00:09

Günter Zöchbauer