我对Angular 2非常陌生,所以请多多包涵。我正在尝试让新组件出现在index.html页面中。该文件集来自GitHub的基本快速入门文件。我这样创建了一个新组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-user-item',
template: `<h1>It works!</h1>`,
})
export class UserItemComponent {
}
我已经这样声明了HTML中的选择器标签:
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
<app-user-item>loading another component</app-user-item>
</body>
</html>
我什至尝试将导入添加到app.module.ts的顶部,并将组件名称添加到app.module.ts中的声明数组。但是仍然没有。我检查了文件结构,发现有一个js版本的user-item.component.ts。但是我看不到变化。
任何帮助,将不胜感激。
干杯
user-item.component.ts:
import { Component } from '@angular/core';
@Component ({
selector: 'app-user-item',
template: `<p>child item</p>`
)}
export class UserItemComponent {
constructor(){ }
}
user.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
template: ` <h2> My User Item </h2>
<app-user-item></app-user-item>`
})
export class UserComponent {
constructor() {}
}
user.module.ts:
import { NgModule } from '@angular/core';
import { UserComponent } from './user-component';
import { UserItemComponent } from './user-item-component';
@NgModule({
declarations: [
UserComponent,
UserItemComponent
]
})
export class UserModule {}
我真的鼓励您使用angular-cli(https://github.com/angular/angular-cli)。并在有角页面上做教程。但是,对于您的用例,上面的代码应该足够并且可以工作。通常,您在与父组件相同的模块中声明子组件。该模块由app.module(根模块)导入
看看Angular的主从组件教程https://angular.io/docs/ts/latest/tutorial/toh-pt2.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句