我需要在Angular 2中使用app.component.ts吗?

5

我正在学习Angular 2,有一个问题:我需要app.component.ts吗?我有很多组件放在文件夹里,每个文件夹都包含组件和模板。但我想知道我是否真的需要主组件,或者可以将其删除?

最好的问候。

2个回答

11

记住:至少需要一个模块和组件才能启动 Angular2 应用程序。

我是否需要 app.component.ts 文件?

并不是必须的。那只是一个.ts文件的名称,它可以是任何其他组件。但请记住,至少需要一个模块和组件才能启动 Angular2 应用程序。

了解以下内容:

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';   //<<<==== it imports AppModule class from app.module.ts file
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);        //<<<===we bootstarp our AppModule here

app.module.ts // .ts文件的名称

//contents are important as it contains @NgModule({}) decorator.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SomeComponent }   from './some.component';  
                                           //<<<===we import SomeComponent class from some.component.ts file to bootstrap it.


@NgModule({
  imports:      [ BrowserModule],
  declarations: [ SomeComponent ],         
  bootstrap:    [ SomeComponent ]          //<<<===we are going to bootstrap/initialize SomeComponent as our first component.
})
export class AppModule { }                 //<<<====we imported AppModule (contains @NgModule decorator) in main.ts as we are going to bootstrap this class which has @NgModule() decorator.

some.component.ts // .ts 文件名称

import { Component } from '@angular/core';
import {UserService} from '../shared/shared.service';
@Component({
  selector: 'my-app',                       //<<<===make sure this matches with custom HTML tag used in index.html
  template: `<h1>Anglar2</h1>  
  `
})
export class SomeComponent {}

谢谢,很高兴你喜欢它。 - micronyks
@micronyks,我们可以将app.module.ts和app.component.ts重命名为其他名称,并在main.ts中进行必要的更改吗? - Michel Gokan Khan
答案是肯定的!我试过了! - Michel Gokan Khan

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接