gpt4 book ai didi

Angular2 - 嵌套组件的编译问题

转载 作者:搜寻专家 更新时间:2023-10-30 21:40:38 24 4
gpt4 key购买 nike

我有两个使用 TypeScript 编码的 Angular2 组件:

app/app.component.ts

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

@Component({
selector: 'my-app',
styles : [`
.parent {
background : #c7c7c7;
color : #000;
padding: 20px;
}
`],
template: `
<div class="parent">
<h1>{{name}}</h1>
</div>
`,
})
export class AppComponent { name = 'Angular'; }

app/child.components.ts

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

@Component({
selector: 'child-component',
styles : [`
.child {
background : #aaa;
padding: 10px;
}
`],
template: `
<div class="child">
<h2>{{name}}</h2>
</div>
`,
})
export class ChildComponent {
name = "Child Component";
}

如果在组件 app/app.component.ts 中我没有嵌套组件:app/child.components.ts 一切都正确编译。

请检查这里:

http://plnkr.co/edit/5PfPmDoUkxYRirCtwSGa?p=preview&open=app%2Fapp.component.ts

但是如果我嵌套它,那么我认为转译器无法编译...

app/app.component.ts (nesting: app/child.components.ts)

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

@Component({
selector: 'my-app',
styles : [`
.parent {
background : #c7c7c7;
color : #000;
padding: 20px;
}
`],
template: `
<div class="parent">
<h1>{{name}}</h1>
<child-component></child-component>
</div>
`,
directives: [ChildComponent]
})
export class AppComponent { name = 'Angular'; }

请检查这里:

http://plnkr.co/edit/qpsYQx4Ih4qQ1dyk3tFH?p=preview&open=app%2Fapp.component.ts

我的问题是:

1- 上面的代码有什么问题?

2- 有没有一种方法可以检查 TypeScript 转译器的错误日志,以了解在出现类似此处的转译问题时发生了什么?

最佳答案

嗯,今天感觉不错 ;)

您的应用程序中缺少两大块。顺便说一句,Plunker 已经预设了 Angular 2 模板,您可以从中开始尝试。所以您缺少的是 NgModule 和 main.ts 文件。

您可以阅读有关 NgModule 的更多信息 here ,但作为该页面的摘录:

An Angular module is a class decorated with @NgModule metadata.

The metadata:

  • declare which components, directives and pipes belong to the module.
  • make some of those classes public so that other component templates can use them.
  • import other modules with the components, directives and pipes needed by the components in this module.
  • provide services at the application level that any application component can use.

既然有子组件,还需要加上CUSTOM_ELEMENTS_SCHEMA ,因为你有 <child-component>标签,即元素。这是适合你的 NgModule,非常小:

@NgModule({
imports: [
BrowserModule,
],
declarations: [
AppComponent
ChildComponent,
],
bootstrap: [ AppComponent ],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})

export class AppModule { }

其他丢失的文件是启动应用程序的 main.ts。

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)

您的组件几乎是正确的。但是我们不再使用“指令”,一切都在 NgModule 中处理。

这是一个 Plunker

正如我所说,我真的建议您从 Angular.io 的教程开始。我认为该教程非常好!

关于Angular2 - 嵌套组件的编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41638794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com