Angularv4.初体验


879 浏览 3 years, 10 months

4 创建新组件 Ng Generate New Component

版权声明: 转载请注明出处 http://www.codingsoho.com/

04 Ng Generate New Component

创建组件命令ng g component

我们先创建两个组件:列表list和详情detail。这也是CRDU里最基本的两个视图

ng g component videoList
ng g component video-detail

生成的文件如下

  create src/app/video-list/video-list.component.html (29 bytes)
  create src/app/video-list/video-list.component.spec.ts (650 bytes)
  create src/app/video-list/video-list.component.ts (284 bytes)
  create src/app/video-list/video-list.component.css (0 bytes)
  update src/app/app.module.ts (412 bytes)

它会创建两个app文件夹video-list和video-detail,这儿videoList自动转成了video-list,文件夹下的文件跟初始化之后是一样的,以video-detail为例

video-detail.component.css
video-detail.component.html
video-detail.component.spec.ts
video-detail.component.ts

html: 模板文件
ts:typescript脚本文件
css: 样式
spec.ts: ?

同时它自动更新app.module.ts,将新创建的Component添加进去

@NgModule({
  declarations: [
    AppComponent,
    VideoListComponent,                // (1)
    VideoDetailComponent               // (2)
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]            // (3)
})

(1)(2) declarations里VideoListComponent和VideoDetailComponent是新添加的两个component
(3) 在modules里,AppComponent是主Component,我们也可以修改videoList为主Component

bootstrap: [VideoListComponent]

如果想修改主页为video-list视图,可以在index.html修改selector,将srvup-root相应地改为videoList的"video-list”

<body>
  <video-list></video-list>
</body>

对应的selector在video-list.component.ts文件定义

@Component({
  selector: 'video-list',
  templateUrl: './video-list.component.html',
  styleUrls: ['./video-list.component.css'],
})

上面只是交给了大家一种方法,实际工作中一般不推荐修改,因为需要尽量保持一致性,以便其他开发者能够快速的阅读和开发代码