3

I did a mistake in my Angular2 class and I've not clearly understood about @Input.

I created 2 components AppComponent and AppDetailComponent.

In AppDetailComponent :

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


@Component ({
selector: 'app-detail',
template: 'Hi {{datainput}}'
})

export class AppDetailComponent {

@Input()
datainput: string;

}

and in AppComponent template :

<h1>
  {{title}}
</h1>
<app-detail [datainput]="'test'"></app-detail>

and in App Module I made a mistake by add AppDetailComponent as bootstrap component

import { AppComponent } from './app.component';
import { AppDetailComponent } from './app-detail.component';

@NgModule({
  declarations: [
    AppComponent, AppDetailComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent, AppDetailComponent]
})
export class AppModule { }

After I removed AppDetailComponent from the bootstrap list, program was working correctly.

I don't understand why @input dose not working when I use it as bootstrap component?

Will Angular always ignore input property in spite of I send the input from an other angular component?

2 Answers2

1

@Inputs() can only be bound in templates of a component. Bootstrapped component are in index.html outside of any other component and therefore there it's not possible to bind to inputs.

See also Angular 2 external inputs

If you don't have a matching selector in index.html and don't want to use a component as root component, then don't add it to bootstrap: [...]

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I'm not sure I understand you correctly. I didn't add input in index.html but app.component.html which declared as templateUrl of AppComponent – user2930562 Feb 23 '17 at 10:35
  • Why did you add `AppDetailComponent` to `bootstrap: []` then? – Günter Zöchbauer Feb 23 '17 at 10:39
  • Thank you. I did a mistake but I want to know a reason. I try to check javascript file but I found nothing. – user2930562 Feb 23 '17 at 10:47
  • I don't know what you mean. Angular just doesn't support input in root components and `bootstrap` is for registering root components. There is no point generating code for something that's not supposed to do anything. – Günter Zöchbauer Feb 23 '17 at 10:50
0

you need to bootstrap only the AppComponent.

import { AppComponent } from './app.component';
import { AppDetailComponent } from './app-detail.component';

@NgModule({
  declarations: [AppComponent, AppDetailComponent],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32