I want to pass an object from app.component to a child component (home.component). Am I using routing the wrong way and that's why the child component I want to pass the object to is being rendered twice? How can I avoid it? I guess that might also be the reason why that object is undefined the second time the component is rendered.
I've been googling for several days now and nothing seems to work. I was following a video tutorial but it was based on Angular 2 RC3 or earlier I guess. I am using Angular 2.1.1
If I remove the line below, the child component is generated only once. But then I can't pass the object to it.
<app-home [testdata]="testdata"></app-home>
Here's the code:
app.component.ts:
import { Component, Output } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
title = 'Welcome';
testdata = {
somedata: 'Here is the data'
};
}
app.component.html:
<header>
<h1>
{{title}}
</h1>
<nav>
<ul>
<li><a routerLink="/" routerLinkActive="active">Home</a></li>
<li><a routerLink="/directory">Directory</a></li>
</ul>
</nav>
</header>
<section id="main">
<app-home [testdata]="testdata"></app-home>
<router-outlet></router-outlet>
</section>
home.component.ts:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.css']
})
export class HomeComponent implements OnInit {
homeTitle = "Welcome to the homepage";
@Input() testdata: any;
constructor() {
}
ngOnInit() {
}
}
app.routes.ts:
import { Routes, RouterModule } from "@angular/router";
import { DirectoryComponent } from "./directory/directory.component";
import { HomeComponent } from "./home/home.component";
const APP_ROUTES = [
{ path: '', component: HomeComponent }
];
export const APP_ROUTES_PROVIDER = RouterModule.forRoot(APP_ROUTES);
main.ts:
import './polyfills.ts';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';
import { APP_ROUTES_PROVIDER } from './app/app.routes';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule, [APP_ROUTES_PROVIDER]);
That's a known issue
Binding currently just doesn't work with components added dynamically. But you can pass data imperatively like:
app.component.html
app.component.ts
Plunker Example
This also might be related