0

I am using angular2-universal-starter project.

So i was trying to pass an object to a child component using @Input , but its not working correctly.

I have used dynamic component loader to load child component and I want to pass the object to child component.

Following is my code snippet:

app.component.ts

import {Component, Directive, Renderer, DynamicComponentLoader, ElementRef} from 'angular2/core';
import {Http} from 'angular2/http';    
import {headingComponent} from './heading.component';
@Directive({
  selector: '[x-large]'
})
export class XLarge {
  constructor(element: ElementRef, renderer: Renderer) {
    // we must interact with the dom through Renderer for webworker/server to see the changes
    renderer.setElementStyle(element.nativeElement, 'fontSize', 'x-large');
  }
}
@Component({
  selector: 'app',
  directives: [    
    XLarge
  ],  
  template: `
    <div>
        <div>
        <span x-large>Hello, {{ user.name }}!</span>
        </div>
        <icici-heading [user]="user"></icici-heading>      
    </div>
`
})
export class App {
  public user;       
  constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {          
      dcl.loadNextToLocation(headingComponent, elementRef);
  }
  ngOnInit(){
      this.user = { "id": 11, "name": "Mr. Nice" };
  }  
}

heading.component.ts

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

@Component({
    selector: 'icici-heading',
    template: `
        <div>
        <!--{{user.name}}-->this is not working
        {{name}}
       </div>
`   
 })

export class headingComponent implements OnInit {
    @Input() user;
    name: string;
    constructor() { }
    ngOnInit() { 
        this.name="heading is rendered";
    }    
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131

1 Answers1

0

I guess you just need to make your code more forgiving when the value is not yet available.

This will work:

{{user?.name}}

The Elvis or safe-navigation operator only evaluates .name when user != null

For dynamically added components you also need to pass values imperatively

dcl.loadNextToLocation(headingComponent, elementRef)
.then(cmpRef => cmpRef.instance.user = this.user);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567