angular4x学习笔记

前端之家收集整理的这篇文章主要介绍了angular4x学习笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

angular常用命令:
   安装:
     npm install -g @angular/cli
     npm install -g cnpm --registry=https://registry.npm.taobao.org   //安装淘宝镜像
     cnpm install -g @angular/cli
   创建项目:
     ng new 项目名称
     cnpm install //安装依赖
   启动项目:
      ng serve --open可以运行项目

angular:
   Angular 模块类 述应用的部件是如何组合在一起的。 每个应用都至少有一个 Angular 模块,也就 是根模块,
   用来引导并运行应用。你可以为它取任何名字。常规名字是AppModule。 也就是app.module.ts 文件
   引入组件:
   import { BrowserModule } from '@angular/platform-browser'; /*BrowserModule,浏览器解析的模块*/
@NgModule:
   @NgModule 装饰器将 AppModule 标记为 Angular 模块类(也叫 NgModule 类)。
   @NgModule 接受一个元数据对象,告诉 Angular 如何编译和启动应用。
   如:
   @NgModule({
     declarations: [ /*引入当前项目运行的的组件*/
       AppComponent
     ],imports: [ /*引入当前模块运行依赖的其他模块*/
       BrowserModule,FormsModule,HttpModule
     ],providers: [],/*定义的服务 回头放在这个里面*/
       bootstrap:[AppComponent] /*指定应用的主视图(称为根组件)通过引导根AppModule来启动
        应用 ,这里一般写的是根组件*/
   })
export:
   /*根模块不需要导出任何东西, 因为其它组件不需要导入根模块。 但是一定要写*/
   export class AppModule { }


自定义组件的步骤:具体参考https://github.com/angular/angular-cli#generating-components-directives-pipes-and-services
   1,创建组件. 如在components目录下面创建一个header组件
     ng g component components/header
     组件代码如下:
     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() { /*初始化加载的生命周期函数*/
         }
     }
   2,使用组件:根据组件名字引用,如:
     <app-header></app-header>

angualr4.0 绑定数据方法总结:
   1,数据文本绑定: {{}},如:
     <h1> {{title}} <h1>
   2,绑定 html
     this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>"
     <div [innerHTML]="h"></div>
数据循环、绑定数据:
   1,*ngFor,如:遍历list
   <ul>
     <li *ngFor="let item of list">
        {{item}}
     </li>
   </ul>

   2,循环的时候设置 key:
   <ul>
     <li *ngFor="let item of list;let i = index;">
         {{item}} --{{i}}
     </li>
   </ul>
   3,template循环数据
   <ul>
      <li template="ngFor let item of list">
        {{item}}
      </li>
   </ul>
   4,条件判断*ngIf
    <p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p>
    <p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p>
   5,执行事件 (click)=”getData()”
    .html文件:
    <button class="button" (click)="getData()">
       点击按钮触发事件
    </button>
    <button class="button" (click)="setData()">
       点击按钮设置数据
    </button>

    .ts文件
    getData(){ /*自定义方法获取数据*/ //获取
       alert(this.msg);
    }
    setData(){ //设置值
       this.msg='这是设置的值';
    }
   6,绑定属性,例如给div中的id与title绑定属性
     <div [id]="id" [title]="msg">调试工具看看我的属性</div>
   7,事件绑定 、 表单处理
     html文件: <input type="text" (keyup)="keyUpFn($event)"/>
     .ts文件:
     keyUpFn(e){
       console.log(e)
     }
   8,双向数据绑定
      <input type="text" [(ngModel)]="inputValue"/>
      {{inputValue}}
   9,Todolist 功能

Angular4.x 创建使用服务:
   一、 命令创建服务
    ng g service my-new-service
    创建到指 定目录 下面
    ng g service services/storage
   二、app.module.ts 里面引入创建的服务
    1,app.module.ts 里面引入创建的服务
       import { StorageService } from './services/storage.service';
    2,NgModule 里面的 providers 里面依赖注入服务
       @NgModule({
         ...
         providers: [StorageService]
         ...
       })
   三、使用的页面引入服务,注册服务
        import { StorageService } from '../../services/storage.service';  /*引入服务*/
        //private storage:StorageService  依赖注入服务
        constructor(private storage:StorageService) {//注入服务
            console.log(this.storage);
            // this.storage.setItem('username','张三');
            // alert(this.storage.getItem('username'));
        }

      使用storage服务:
      addData(){
        this.storage.set('todolist',this.list);
      }

Angular4.x get post 以及 jsonp 请求网络数据,不用 RxJs
  一、app.module.ts 注册 HTTP JSONP 服务
  1.引入 HttpModule 、JsonpModule
   import { HttpModule,JsonpModule } from '@angular/http';
  2,HttpModule 、JsonpModule 依赖注入
  @NgModule({
   ...
   imports: [
     ..
     HttpModule,JsonpModule,..
   ],...
  })

 二、通过 Http、Jsonp 请求数据、不用 RxJs
   1、在需要请求数据的地方引入 Http
   import {Http,Jsonp} from "@angular/http";
   2、构造函数内 申明:
   constructor(private http:Http,private jsonp:Jsonp) { }
   3、对应的方法内使用 http 请求数据,如:
     requestData(){
       var _that=this;
       // alert('请求数据');
       var url="http://www.phonegap100.com/appapi.PHP?a=getPortalList&catid=20&page=1";
       this.http.get(url).subscribe(function(data){
          var list=JSON.parse(data['_body']);
       },function(err){
           console.log(err);
       })
     }
三、使用 Post请求
  1. 引入 Headers 、Http 模块
  import {Http,Jsonp,Headers} from "@angular/http";
  2. 实例化 Headers
  private headers = new Headers({'Content-Type': 'application/json'});
  3,post提交数据:
    postData(){
      // 1.import { Http,Headers } from '@angular/http';   Headers 定义请求头的
      //2.private headers = new Headers({'Content-Type': 'application/json'});
      //3.post提交数据

      var url="http://127.0.0.1:3000/dologin";
      this.http.post(url,JSON.stringify({"username":'zhangsan',"age":'20'}),{headers:this.headers}).subscribe(function(data){
          console.log(data);
        },function(error){
            console.log(error);
        })
    }

四、通过 Http、Jsonp 请求数据、使用 RxJs。
  1、 引入 Http 、Jsonp、RxJs 模块
  import {Http,Jsonp} from "@angular/http";
  import {Observable} from "rxjs";
  import "rxjs/Rx";
  2、 构造函数内申明:
  constructor(private http:Http,private jsonp:Jsonp) { }
  3,get请求:
  this.http.get("http://www.phonegap100.com/appapi.PHP?a=getPortalList&catid=20&p age=1")
    .map(res => res.json()) .subscribe(
    function(data){ console.log(data);
    }
  );
  http.get 方法中返回一个 Observable 对象,我们之后调用 RxJS 的 map 操作符对返回的数据 做处理。

  Jsonp 请求:
  this.jsonp.get("http://www.phonegap100.com/appapi.PHP?a=getPortalList&catid=20&page
  =1&callback=JSONP_CALLBACK")
  .map(res => res.json()) .subscribe(
     function(data){ console.log(data);
  } );


父子组件的传值:
一、父组件给子组件传值 -@Input
  1. 父组件调用子组件的时候传入数据
  <app-header [msg]="msg"></app-header>
  2. 子组件引入 Input 模块
  import { Component,OnInit,Input } from '@angular/core';
  3. 子组件中 @Input 接收父组件传过来的数据
  export class HeaderComponent implements OnInit {
    @Input() msg:string
    constructor() { }
    ngOnInit() {
    }
  }
  4. 子组件中使用父组 件的数据
  <h2>这是头部组件--{{msg}}</h2>

二、父子组件传值的方式让子组件执行父组件的方法
  1. 父组件定义方法
  run(){
    alert('这是父组件的 run 方法');
  }
  2.调用子组件 传入当前方法
  <app-header [msg]="msg" [run]="run"></app-header>
  3. 子组件接收父组件 传过来的方法
  import { Component,Input } from '@angular/core';
  @Input() run:any;//*********

  export class HeaderComponent implements OnInit {
    @Input() msg:string
    @Input() run:any;//*********
    constructor() { }
  }
  4. 子组件使用父组件 的方法。
  export class HeaderComponent implements OnInit {
    @Input() msg:string;
    @Input() run:any;
    constructor() { }
    ngOnInit() {
       this.run(); /*子组件调用父组件的 run 方法*/
    }
  }
三、子组件通过@Output 执行父组件的方法
  1. 子组件引入 Output 和 EventEmitter
   import { Component,Input,Output,EventEmitter} from '@angular/core';
  2.子组件中实例化 EventEmitter
  @Output() private outer=new EventEmitter<string>(); /*用EventEmitter和output装饰器配合使用 <string>指定类型变量*/
  3. 子组件通过 EventEmitter 对象 outer 实例广播数据
  sendParent(){
    // alert('zhixing');
    this.outer.emit('msg from child')
  }
  4.父组件调用子组件的时候,定义接收事件,outer 就是子组件的 EventEmitter 对象 outer
  <app-header (outer)="runParent($event)"></app-header>
  5.父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
  //接收子组件传递过来的数据
  runParent(msg:string){
    alert(msg);
  }
四、父组件通过局部变量获取子组件的引用 ,主动获取子组件的数据和方法(一)

五、父组件通过局部变量获取子组件的引用,通过 ViewChild 主动获取子组件的数 据和方法


Angular4.x 中的路由:
一、Angular 命令创建一个配置好路由的项 目
1. 命令创建项目
   ng new demo02 –-routing
2. 创建需要的组件
   ng g component home
   ng g component news
   ng g component newscontent
3. 找到 app-routing.module.ts 配置路由

   const routes: Routes = [
     //{
     //  path: '',//  children: []
     //}
     {path: 'home',component: HomeComponent},{path: 'news',component: NewsComponent},{path: 'newscontent/:id',component: NewscontentComponent},{
       path: '',redirectTo: '/home',pathMatch: 'full'
     }

   ];
4. 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由
   <h1>
      <a routerLink="/home">首页</a>
      <a routerLink="/news">新闻</a>
   </h1>
   <router-outlet></router-outlet>

二、Angula4.x 在已有的项目中配置路由
1. 新建组件
   ng g component home
   ng g component news
   ng g component newscontent
2. 新建 app-routing.module.ts,app-routing.module.ts 中引入模块
   import { NgModule } from '@angular/core';
   import { Routes,RouterModule } from '@angular/router';
3. app-routing.module.ts 中引入组件
   import { HomeComponent } from './home/home.component';
   import { NewsComponent } from './news/news.component';
   import { NewscontentComponent } from './newscontent/newscontent.component';
4. app-routing.module.ts 中配置组件
   const routes: Routes = [
     {path: 'home',pathMatch: 'full'
     }
   ];
5. app-routing.module.ts 中配置模块 暴露模块
  @NgModule({
    imports: [RouterModule.forRoot(routes)],exports: [RouterModule]
    export class AppRoutingModule { }
  })
6.app.module.ts 里面的 import 注册这个路由模块
  import { AppRoutingModule } from './app-routing.module';
7.app.module.ts 里面的 import 注册这个路由模块
  imports: [
    BrowserModule,AppRoutingModule
  ]
8.找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由
  {{title}}
    <a routerLink="/home">首页</a>
    <a routerLink="/news">新闻</a>
  </h1>
  <router-outlet></router-outlet>

三、Angular routerLink 页面跳转 默认跳 转路由
   //刚进来路由为空跳转的路由
    {
      path:'',redirectTo:'home',pathMatch:"full"
    }

    //匹配不到路由的时候加载的组件 或者跳转的路由
    {
      path: '**',/*任意的路由*/
      // component:HomeComponent
      redirectTo: 'home'
    }
四、Angular routerLinkActive 设置 routerLink 默认选中路由
   <h1>
      <a routerLink="/home" routerLinkActive="active">首页</a>
      <a routerLink="/news" routerLinkActive="active">新闻</a>
   </h1>
   .active{
      color:red;
   }
五、路由的动态传值
1.配置动态路由
   const routes: Routes = [
     {path: 'home',//动态路由
     {
       path: '',pathMatch: 'full'
     }
   ];
2.获取动态路由的值
   import { Router,ActivatedRoute,Params } from '@angular/router';
   constructor( private route: ActivatedRoute) {}
   ngOnInit() {
      console.log(this.route.params);//
      this.route.params.subscribe(data=>this.id=data.id);
   }
六、路由的 js 跳转
1,引入
  import { Router } from '@angular/router';
2.初 始化
  export class HomeComponent implements OnInit {
    constructor(private router:Router) { }  /*声明*/
    ngOnInit() {
    }
    goNews(){
      alert('goNews');
      //js跳转路由
      // this.router.navigate(['/news']);
       this.router.navigate(['/newscontent','123']);
    }

  }
3,跳转
  this.router.navigate(['/news',hero.id]);
七、路由的 js 跳转 get 传值
   constructor(private route: ActivatedRoute) {
      console.log(this.route.queryParams);
   }
八、父子路由
   //引入组件
   import { HomeComponent } from './components/home/home.component';
   import { ShopComponent } from './components/shop/shop.component';

   import { WelcomeComponent } from './components/welcome/welcome.component';
   import { ShoplistComponent } from './components/shoplist/shoplist.component';
   import { ShopcateComponent } from './components/shopcate/shopcate.component';

   //配置路由
   const routes: Routes = [
     {
       path: 'home',component:HomeComponent,children:[   /*配置子路由*/

         {
           path: 'welcome',component:WelcomeComponent,},{   /*匹配不到路由的时候加载的组件*/
           path: '**',/*任意的路由*/
           // component:HomeComponent
           redirectTo:'welcome'
         }
       ]
     },{
       path: 'shop',component:ShopComponent,children:[
         {
             path: 'shoplist',component:ShoplistComponent,{
             path: 'shopcate',component:ShopcateComponent,/*任意的路由*/
           // component:HomeComponent
           redirectTo:'shoplist'
         }
       ]

     },{   /*匹配不到路由的时候加载的组件*/
       path: '**',/*任意的路由*/
       // component:HomeComponent
       redirectTo:'home'
     }
   ];
原文链接:https://www.f2er.com/angularjs/144851.html

猜你在找的Angularjs相关文章