无法将@Input绑定到子级Angular 2的父级

时间:2017-01-27 19:38:26

标签: angular

我有以下配置:

父Html

<login-info [username]="userInformation"></login-info>

父组件

userInformation:string;

子组件

@Input username: string;

    ngOnInit(){
        this.username = this.loginInfoService.getLoginInformation();
    }

child html

<div>
    {{username}}
</div>

儿童服务

@Injectable()
export class LoginInfoService {

    username:string;

    public getLoginInformation(): string {
        return this.username = "mike";
    }
}

错误:

Can't bind to 'username' since it isn't a known property of 'login-
info'. 1. If 'login-info' is an Angular component and it has 
'username' input, then verify that it is part of this module. 2. If 
'login-info' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to 
the '@NgModule.schemas' of this component to suppress this message. (" 
<sa-route-breadcrumbs></sa-route-breadcrumbs> <login-info [ERROR ->]
[username]="userInformation"></login-info> </div> ")

------------------------------- Update 1 -------------- ----------

创建了NgModule

@NgModule({

    declarations: [LoginInformationComponent],

    schemas: [CUSTOM_ELEMENTS_SCHEMA]

})

export class RibbonModule{

}

1 个答案:

答案 0 :(得分:2)

如果是输入,则无需“获取”数据,即const int

的作业

所以用

@Input()

您已从父级获取值,而无需获取它。

使用父级中的child-components标记,您需要在// note, should be brackets here @Input() username: string; 中添加CUSTOM_ELEMENTS_SCHEMA,告诉Angular它是您创建的自定义标记。因此,将以下行添加到ngModule,您已声明组件(这是您的错误消息所示)。

ngModule

所以你的schemas: [CUSTOM_ELEMENTS_SCHEMA] 应该是这样的:

ngModule