angular6入门笔记

作者: 独立行走的蚂蚁 | 来源:发表于2018-12-13 10:54 被阅读1次

    1.0创建项目

      ng new  my-app   // 建立项目目录
      ng serve --open  //  启动项目
      ng g c product        // 创建组件
    
    

    1.1 ngFor循环和事件

      <ul>
          <li *ngFor="let item for aryList;let i = index" 
                (click)="onClick($event)">
                {{i}}-----{{item.name}}
          </li>
      </ul>
    
    
     export class ProductComponent implements OnInit {
        constructor() { }
        onClick(event) {
            console.log(event)
         }
    
        ngOnInit() {
        }
    
     }
    

    1.2获取dom元素

        <div id="div">一个元素标签</div>
    
    import { Component, ElementRef, ViewChild } from '@angular/core';
    export class ProductComponent implements OnInit {
        constructor(
          private el:ElementRef
        ) { }
        onClick(event) {
            console.log(event)
         }
    
        ngOnInit() {
          this.el.nativeElement.querySelector('#div').style.width = '200px';
        }
    }
      
    

    1.3 ngIf

      <div *ngIf="isShow">我是一个div</div>
    
    
      export class ProductComponent implements OnInit {
         constructor() { }
      
        isShow: boolean=false;
        ngOnInit() {
          this.el.nativeElement.querySelector('#div').style.width = '200px';
        }
    
     }
    
    

    1.4父组件给子组件传递数据
    1.4.1 父组件

      <div class="box">
         <h3>ant h3</h3>
         <app-box [num]=100></app-box>
      </div>
    
    

    1.4.2子组件

      <div class="box-children">
        <h4>ant \(^o^)/~</h4>
        <h4>{{num}}</h4>
      </div>
    
    
      @Component({
         selector: 'box-children',
         templateUrl: './box-children.component.html',
         styleUrls: ['./box-children.component.css']
      })
      export class BoxChildrenComponent implements OnInit {
        @Input() num: Number;  // 用于接受父组件的数据源,要和父组件保持一致是Number类型
         constructor() { }
    
        ngOnInit() {
         }
    
      }
    
    

    1.5 行内样式

      <div class="box">
          <div [ngStyle]="getStyle()">style样式</div>
      </div>
    
    export class BoxComponent implements OnInit {
      constructor() { }
    
      getStyle() {
        return {
          'background': '#ccc',
          'font-size': '20px',
          'color': '#fff'
        }
      }
      ngOnInit() {
      }
    }
    

    1.6 双向数据绑定model

        <div class="box-children">
          <h4>ant \(^o^)/~</h4>
          <input type="text" [(ngModel)]="name">
        </div>
    
    export class BoxComponent implements OnInit {
      constructor() { }
      name: string='李明'
      ngOnInit() {
      }
    }
    

    1.7关于类

      <div class="box">
          <h4 [ngClass]="{box-title: sty.hasTitle}">\(^o^)/~</h4>
      </div>
    
    

    1.8 ViewChild实现调用子组件方法

      <div class="box">
            <div (click)="onClick()">\(^o^)/</div>
      </div>
    
    
      import { Component, OnInit, ViewChild } from '@angular/core';
      import { BoxChildrenComponent } from '../box-children.component'
    
      @Component({
          selector: 'app-box',
          templateUrl: './box.component.html',
          styleUrls: ['./box.component.css']
        })
      export class BoxComponent implements OnInit {
    
        @ViewChild( BoxChildrenComponent) boxChildrenFn: BoxChildrenComponent;
        constructor() { }
        onClickClick() {
          this.boxChildrenFn.testClick()
        }
    
        ngOnInit() {
        }
    
      }
    

    子组件

     import { Component, OnInit, Input, Output } from '@angular/core';
    
    @Component({
      selector: 'box-children',
      templateUrl: './box-children.component.html',
      styleUrls: ['./box-children.component.css']
    })
    export class BoxChildrenComponent implements OnInit {
      constructor() { }
    
      testClick() {
        console.log('我是box-chilren')
      }
    
      ngOnInit() {
      }
    
    }
    

    1.9组件内容的嵌套
    父组件

      <div class="box">
          <h3>\(^o^)/~</h3>
      
      <box-children select="[name=middle]">
        <div class="middle">
          <h4>嵌入内容到子组件, 此h4会嵌入到子组件中</h4>
        </div>
        <div class="bottom">
          <h4>嵌入内容到子组件, 此内容不会到子组件中, 不会显示在页面中</h4>
        </div>
        <div name="top">
          <h5>嵌入内容到子组件, 此h5会嵌入到子组件中</h5>
        </div>
      </box-chidren>
    </div>
    

    子组件

      <div class="box-children">
        <ng-content select="[name=top]"></ng-content>
        <ng-content select=".middle"></ng-content>
    </div>
    

    2.0关于input的事件

    <input type="number" name="num" [value]="person.num"  (input)="change($event)" />
    
    person: Object = {
      num: 1
    }
    change(e) :void {
      this.person.num = e.target.value
    }
    

    2.1使用FormsModule

      import { FormsModule } from @angular/forms;
    // 所有模块中都能使用
    @NgModule({
      FormsModule
    })
    

    2.2内置管道

      <div class="pip">
          <span>{{this.mydate | date: "yyyy-mm-dd hh:mm:ss"}}</span>
          <button (click)="getNowTime()">获取当前时间</button>
     </div>
    
    export class MainComponent implements OnInit {
       constructor() {}
       mydate: Object
    
       getNowTime() {
          this.mydate= new Date()
       }
    }
    

    2.3自定义管道
    首先创建一个管道

    ng generate pipe nameLevel
    
    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'nameLevel'
    })
    export class NameLevelPipe implements PipeTransform {
      
      transform(value: Number): String {
        if (value >= 90) {
          return '特级';
        } else if (value >= 80 && value < 90) {
          return '高级';
        } else if (value >= 70 && value < 80) {
          return '一般';
        } else if (value < 70) {
          return '很一般';
        }
      }
    }
    

    使用管道

      <div class="diy-pip">
          <div>{{myScores | nameLevel}}</div>
          <input type="number" [(ngModel)]="myScores" >
      </div>
    
    import { Component, OnInit, Input} from '@angular/core';
    
    @Component({
       selector: 'app-main',
       templateUrl: './main.component.html'
    })
    export class MainComponent implements OnInit {
      constructor() {}
      myScores: Number = 88
    }
    

    2.4 父组件和子组件公用一个服务的

    // 公共的服务 commonService
    import { Injectable } from '@angular/core';
    export class CommonService {
      products: object[] = []
      addProducts(info: Object): void {
        this.products.push(info)
      }
      clearProducts(): void {
        this.products = []
      }
    }
    

    父组件

      <div class="add-product">
      <input type="text" [(ngModel)]="product.title" placeholder="名称">
      <input type="text" [(ngModel)]="product.des" placeholder="详情">
      <input type="text" [(ngModel)]="product.price" placeholder="价格">
      <input type="text" [(ngModel)]="product.addr" placeholder="产地">
      <button (click)="addProducts()">addProducts</button>
    </div>
    <app-main></app-main>
    
    import { Component } from '@angular/core';
    import { CommonService } from './commonService'
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers: [CommonService]
    })
    export class AppComponent {
    
      product: Object = { title: '', des: '', price: '', addr: '' };
      constructor( private _CommonService: CommonService) {}
      addProducts(): void {
        this._CommonService.addProducts(this.product)
      }
    }
    

    子组件

    <div class="common-service">
      <button (click)="getProductList()">获取商品列表</button>
      <li *ngFor="let item of productList">
        <span>{{item.title}}</span> -
        <span>{{item.des}}</span> -
        <span>{{item.price}}</span> -
        <span>{{item.addr}}</span>
      </li>
    </div>
    
    import { Component, OnInit, Input} from '@angular/core';
    import { CommonService } from '../commonService'
    
    @Component({
      selector: 'app-main',
      templateUrl: './main.component.html',
    })
    export class MainComponent implements OnInit {
    
      productList: Array<object>
      constructor( private _CommonService: CommonService) { }
      getProductList(): void {
        this.productList = this._CommonService.products
      }
    }
    

    2.5关于服务器的通信

    npm install --save rxjs  rxjs-compat
    ng generate service ajax
    
    // 在组件引入并注入
    import { HttpModule } from '@angular/http';
    
    @NgModule({
      imports: [
        HttpModule
      ],
    })
    
    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import { Observable } from 'rxjs/Rx';
    import 'rxjs/Rx';
    
    const url_getStudents: string = 'https://127.0.0.1:4000/app'
       
    @Injectable({
       providedIn: 'root'
    })
    export class AjaxService {
      constructor( private _http: Http ) { }
      getPruductList(): Observable<any[]> {
        return this._http.get(url_getStudents)
                  .map(((res) => {
                    console.log('res.json()', res.json())
                    return res.json()
                  }))
      }
    }
    
    <div class="http">
      <button (click)="getPruductList()">get</button>
    </div>
    
    import { Component, OnInit, Input, EventEmitter } from '@angular/core';
    import { CommonService } from '../commonService'
    import { AjaxService } from '../ajax.service'
    
    @Component({
       selector: 'app-main',
       templateUrl: './main.component.html',
       styleUrls: ['./main.component.css']
    })
    export class MainComponent implements OnInit {
      constructor( 
        private _AjaxService: AjaxService
      ) { }
    
      getPruductList(): void {
        this._AjaxService.getPruductList().subscribe(contacts => {
          console.log('contactss', contacts)
        }, err => {
          console.log('err', err)
        })
      }
    }
    

    2.6生命周期
    父组件

      <div class="box">
          <h2>box</h2>
          <button (click)="addBoxNum()">改变num</button>
          <app-box-child [num]="boxNum"></app-box-child>
      </div>
    
    import { Component, OnInit, ViewChild } from '@angular/core';
    import { BoxChildrenComponent } from '../box-children.component'
    
    @Component({
       selector: 'app-box',
       templateUrl: './box.component.html',
       styleUrls: ['./box.component.css']
    })
    export class BoxComponent implements OnInit {
      @ViewChild(BoxChildrenComponent) boxChildrenFn: BoxChildrenComponent;
       constructor() { }
    
       addBoxNum(): void {
         this.boxNum += 1
       }
    
      boxNum: Number = 12
      ngOnInit() {
      }
    
    }
    

    子组件

      <div class="box-child">
          <h4>父组件传过来的num: {{num}}</h4>
      </div>
    
     import { Component, OnInit, Input } from '@angular/core';
    @Component({
      selector: 'box-children',
      templateUrl: './box-children.component.html',
    })
    export class BoxChildrenComponent implements OnInit {
    
      @Input() num: Number;
    
      ngOnChanges(data): void {
        console.log('父元素传过来的值改变了啊', data)
      }
      constructor() { }
      ngOnInit() {
      }
    }
    

    2.7 关于ngOnInit
    该方法(钩子)内可用于获取数据, 有点类似于vue的created

    2.8路由

    import { Routes } from '@angular/router'
    import { ListComponent } from './list/list.component'
    export const rootRouterConfig: Routes = [
      {path: 'list', component: ListComponent}
    ]
    
    import { rootRouterConfig } from './app.routes'
    import { NgModule, ModuleWithProviders } from '@angular/core'
    import { RouterModule } from '@angular/router'
    
    let rootRouteModule:ModuleWithProviders = RouterModule.forRoot(rootRouterConfig)
    
    @NgModule({
      imports: [
        rootRouteModule
      ]
    })
    
    export class AppModule { }
    
    <div class="route">
        <h3>route</h3>
        <a [routerLink]="['/list']">goto-list</a>
        <router-outlet></router-outlet>
    </div>
    

    2.9关于路由的routerLinkActive

    <div routerLinkActive="active">
      <a [routerLink]="['/list']">goto-list</a>
    </div>
    <div routerLinkActive="atv">
      <a [routerLink]="['/detail']">goto-detail</a>
    </div>
    
    .active {
      background: #ccc;
    }
    

    3.0关于路由的跳转

    // 默认路由的跳转
    import { Router } from '@angular/router'
    
    export class AppComponent {
      constructor( 
        private router: Router
      ) {
        router.navigate('/list')
      }
    
    }
    
      <div class="div" (click)="goList()">路由跳转</div>
    
    import { Router } from '@angular/router'
    export class AppComponent {
    
      constructor( 
        private router: Router
      ) {}
    
      goList(){
       // js带参数的路由的跳转
       this.router.navigate(['/list'], {queryParams: {num: 10}}) 
      }
    }
    
    // 实现路由带参数
    // 页面
    <a [routerLink]="['/list']" [queryParams] = "{num: 10}">走一个</a>
    
    // js
    this.router.navigate(['/list'], {queryParams: {num: 10}})或
    this.router.navigateByUrl('/list?num=10')
    

    3.1获取路由的参数

    <div routerLinkActive="active">
      <a [routerLink]="['/detail']" 
           [queryParams] = "{num: 10, from: 'shanghai', add: '中央大街'}">
          跳转
      </a>
    </div>
    
    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router'
    
    @Component({
      selector: 'app-detail',
      templateUrl: './detail.component.html',
      styleUrls: ['./detail.component.css']
    })
    export class DetailComponent implements OnInit {
      constructor(
        private activatedRoute: ActivatedRoute
      ) {}
    
      ngOnInit() {
        this.activatedRoute.queryParams.subscribe(params => {
          console.log(params)  // {num: "10", from: "shanghai", add: "中央大街"}
        })
      }
    }
    

    3.2子路由

    import { Routes } from '@angular/router'
    import { DetailComponent } from './detail/detail.component'
    import { InfoComponent } from './info/info.component'
    
    export const rootRouterConfig: Routes = [
      {path: 'detail', component: DetailComponent, children: [
        // path为空表示默认显示的路由
        // {path: '', component: Info2Component}
        {path: 'info', component: InfoComponent}
      ]}
    ]
    
      <div class="detail">
          <h3>detail-component</h3>
          <a [routerLink]="['/detail/info']" [queryParams] = "{name: 'liming'}">点击详情</a>
          <router-outlet></router-outlet>
     </div>
    

    3.3附属路由
    同一个页面只能有一个router-outlet , 可以有多个附属路由

    import { Routes } from '@angular/router'
    import { DetailComponent } from './detail/detail.component'
    import { InfoComponent } from './info/info.component'
    
    export const rootRouterConfig: Routes = [
      {path: 'detail', component: DetailComponent, children: [
        {path: 'info', component: InfoComponent},
        {path: 'add', component: AddComponent, outlet='card'},
        {path: 'age', component: AgeComponent, outlet='card'}
      ]}
    ]
    
    <div class="detail">
      <h3>detail-component</h3>
      <a [routerLink]="['/detail/info']" [queryParams] = "{name: 'tom'}">点击详情</a>
      <router-outlet></router-outlet>
      <router-outlet name="card"></router-outlet>
    </div>
    

    相关文章

      网友评论

        本文标题:angular6入门笔记

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