ng4快速入门

作者: 简小咖 | 来源:发表于2017-10-06 14:15 被阅读64次

    英文官网 https://angular.io/
    中文官网 https://angular.cn/

    验证

    行命令node -vnpm -v, 来验证一下你正在运行 node 6.9.x 和 npm 3.x.x 以上的版本。
    更老的版本可能会出现错误,更新的版本则没问题。

    全局安装Angular CLI

    npm install -g @angular/cli
    

    创建新项目

    ng new my-app
    

    请耐心等待。 创建新项目需要花费很多时间,大多数时候都是在安装那些npm包。

    启动

    cd my-app
    ng serve --open
    

    ng serve命令会启动开发服务器,监听文件变化,并在修改这些文件时重新构建此应用。
    使用--open(或-o)参数可以自动打开浏览器并访问http://localhost:4200/

    image.png

    目录结构

    package.json 是任何一个基于node的项目必须有的配置文件,这个文件记录工程信息:名字、版本号、依赖的包
    src目录:代码文件都放在整个文件中,把精力放在该目录

    app.module.ts

    /*引入组件*/ 
    import { BrowserModule } from '@angular/platform-browser'; 
    /*BrowserModule,浏览器解析的模块*/ 
    import { NgModule } from '@angular/core'; 
    /*angualrjs核心模块*/
    import { AppComponent } from './app.component';
     /*自定义  根组件*/ 
    @NgModule({ 
    declarations: [       /*引入当前项目运行的的组件*/
         AppComponent
     ],
     imports: [         /*引入当前模块运行依赖的其他模块*/ 
    BrowserModule, FormsModule, HttpModule 
    ],
    providers: [],    /*定义的服务*/
    bootstrap: [AppComponent] 
    /* 指定应用的主视图(称为根组件) 通过引导根AppModule来启动应用 ,
    这里一般写的是根组件*/
     })
    

    App.component.ts

    import { Component } from '@angular/core'; /*引入angular核心*/
     @Component({ 
    selector: 'app-root',       /*使用这个组件的名称*/
    templateUrl: './header.component.html',     /*html模板*/ 
    styleUrls: ['./header.component.css']        /*css样式*/ 
    }) 
    export class AppComponent {   /*数据*/
    }
    

    创建组件

    ng g component components/header
    自动生成文件结构:

    image.png
    生成文件中的.spec.ts文件没什么用,可以删掉

    header.component.ts

    import { Component, OnInit } from '@angular/core'; 
    /*引入angular核心*/ 
    @Component({ 
    selector: 'app-header', /*使用这个组件的名称*/ 
    templateUrl: './header.component.html', /*html模板*/ 
    styleUrls: ['./header.component.css'] /*css样式*/ 
    })
    export class HeaderComponent implements OnInit { /*实现接口*/ 
    constructor() { /*构造函数*/ } 
    ngOnInit() { /*初始化加载的生命周期函数*/ } 
    }
    

    组件使用

    <app-header></app-header>
    selector中定义的名称,直接做元素来使用,就可以啦

    相关文章

      网友评论

        本文标题:ng4快速入门

        本文链接:https://www.haomeiwen.com/subject/xzalyxtx.html