Angular @Input is not working with bootstrap component

[亡魂溺海] 提交于 2019-12-11 03:17:50

问题


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?


回答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: [...]




回答2:


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 { }


来源:https://stackoverflow.com/questions/42412603/angular-input-is-not-working-with-bootstrap-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!