【问题标题】:Can we use a component inside another component in current version of Angular2?在当前版本的 Angular2 中,我们可以在另一个组件中使用一个组件吗?
【发布时间】:2016-12-01 22:58:32
【问题描述】:

我希望在 angular2 当前版本(V2.2.0)中的另一个组件中使用组件

但之前我们可以选择使用以下代码在另一个组件中使用组件。

import { AnotherComponent } from './another-component';

@Component({
  selector: 'my-component',
  directives: [AnotherComponent],
  template: '<div>Something there<another></another></div>'
})
export class OtherComponent {
}

但是当我尝试相同时它不起作用,它会引发模板编译错误。

现在是否删除了此功能? 或者 还有另一种方法吗?

错误信息

  1. 如果“导航”是一个 Angular 组件,则验证它是该模块的一部分。
  2. 如果“导航”是 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas” 压制此消息。 ("

【问题讨论】:

  • 你能添加你的错误信息吗?

标签: angular angular2-template


【解决方案1】:

你必须在 declarations 的父 Module 中添加AnotherComponent

declarations: [
  AnotherComponent 
]

【讨论】:

  • 但我们没有名称声明组件的属性?
  • 那么你必须添加属性;)
【解决方案2】:

用你的所有组件制作一个像这样的文件

import {
    LoginComponent
} from './loginComponent/login.component';
import {
    adduserComponent
} from './core/adduserComponent/adduser.component';
import {
    TemplateComponent
} from './core/template.component';
import {
    DashboardComponent
} from './core/dashboard/dashboard';
import {
   HeadComponent
} from './core/headComponent/head.component';


export const ALL_DECLARATIONS = [
    LoginComponent,
    adduserComponent,
    TemplateComponent,
    HeadComponent,
    ChangeHeadComponent
];

并在您的父模块文件中导入 ALL_DECLARATIONS

import { ALL_DECLARATIONS } from './filename';

并使用

    @NgModule({
        imports: [
            BrowserModule,
            FormsModule,
            ReactiveFormsModule,
            RouterModule.forRoot(routes),
        ],
        declarations: [
            AppComponent,
            ...ALL_DECLARATIONS
        ],
        providers: [
            ...ROUTES_PROVIDERS
        ],
        bootstrap: [
            AppComponent
        ]
    })
export class AppModule {}

使用Spread Operator,因此您不必在模块文件中导入所有组件文件

let cde = ['c', 'd', 'e'];
let scale = ['a', 'b', ...cde, 'f', 'g'];  // ['a', 'b', 'c', 'd', 'e', 'f', 'g']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2020-12-04
    • 2023-02-14
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多