kunyashaw博客主页 关注kunyashaw新博客 关于kunyashaw 转到底部

angualr基础

一、Angular概述

基于命令行的开发方式?
①hot reload
②编译工作
③集成了webpack打包工具
。。。。


angular.cn 中文
angular.io 正式官网
angular.cn/guide/styleguide 风格指南

1、what?
angular是一个Google推出的js框架,是以模块为基本单位,模块又可以包含组件、指令、过滤器。。

1.1 版本问题
angular angular2.0以后所有的版本统称为angular
(当前学习ng4.0)

angular.js angular1.* 统称为angular.js
(http://www.runoob.com/angularjs/angularjs-tutorial.html)

1.2 版本之间的区别
①新版本是有组件的概念的
②老版本是$scope和controller为主
③angular引入了rxjs
④angular采用ts(typescript是es6的超集,是由微软和谷歌) ts是一种强类型检查机制的语言
⑤angular可读性、提高了代码的复用率、维护成本变低。。。

2、where
可以使用支持angular的Ionic框架来实现移动端的开发,直接使用angular来实现pc端的开发

实现操作比较频繁的SPA

3、why
①遵循w3c所推出的webComponent标准(组件化)
②代码具有更好的可读性和可维护性、
③引入了更多的高效率的工具 ,比如rxjs\immutable.js。。。, 让代码的编译、部署更简单
④ts --》 健壮

4、how
用 Angular 扩展语法编写 HTML 模板,
用组件类管理这些模板,
用服务添加应用逻辑,
用模块打包发布组件与服务。

angular的开发整体框架,是有8大组成部分构成:
①组件:定义视图

②服务:将经常用到的数据和方法封装在一个类中;这能让你的代码更加模块化、可复用,而且高效

③依赖注入(DI): 服务的元数据提供了一些信息,Angular 要用这些信息来让组件可以通过使用该服务

④装饰器:用来描述当前这个类是一个什么样的类 @Component @NgModule @Pipe @Directive @Injectable

⑤模板:普通的 HTML 和指令与绑定标记(markup)组合起来

⑥指令:模板中的指令会提供程序逻辑
循环、条件判断。。。

⑦数据绑定:绑定标记会把你应用中的数据和 DOM 连接在一起。
①事件绑定让你的应用可以通过更新应用的数据来响应目标环境下的用户输入。
②属性绑定让你将从应用数据中计算出来的值插入到 HTML 中。
③双向数据绑定

⑧管道:转换要显示的值以增强用户体验

搭建环境的方式:
方式1:
①下载quickstart-master.zip压缩包
https://github.com/angular/quickstart download
或者 直接拷贝老师提供的压缩包
②解压缩 压缩包,进入对应的目录中
执行npm install 安装项目所需要用到的依赖
③npm start 启动开发服务器

方式2:
Angular CLI是一个命令行界面工具,它可以创建项目、添加文件以及执行一大堆开发任务,比如测试、打包和发布。
//安装基于angular的命令工具
npm install -g @angular/cli
//创建一个有着ng模板的项目
ng new my-app
//进入当前目录下的my-app
cd my-app
//启动开发服务器
ng serve --open

 

 

 

 

 

①创建文件 app/test/test.component.ts
 
        ②将类装饰成一个组件类
            import {Component} from '@angular/core'
       
            @Component({
                selector:'test',
                template:`<h1>it is a test</h1>`
            })
 
            export class Demo01Component{
            }
        ③使用组件
            ①到模块中声明
                app.module.ts中,
                import {TestComponent} from './test/test.component'
 
                @NgModule({
                    declarations:[TestComponent]
                })
            ②<test></test>
demo01
<wiz_code_mirror>
 
 
 
 
 
//  组件是可被反复使用的,带有特定功能的视图 
 
import {Component}  from '@angular/core'
 
@Component({
    selector:'demo01',
    template:'<h1>this is our first component</h1>'
})
 
export class Demo01Component{
 
}
 
 
 
demo02_lianxi
 
<wiz_code_mirror>
 
 
 
 
 
import {Component} from '@angular/core'
 
@Component({
    selector:'demo02',
    template:`<ul>
        <li>test01</li>              
        <li>test02</li>              
        <li>test03</li>              
        <li>test04</li>              
        <li>test05</li>              
    </ul>`
})
 
export class Demo02Component{}
 
 
 
 
demo03_for
<wiz_code_mirror>
 
 
 
 
 
import {Component} from '@angular/core'
 
@Component({
    selector:'demo03',
    template:`
        <h1>这是demo03</h1>
        <ul>
            <ng-container *ngFor="let tmp of list;let myIndex=index" >
            <li 
           *ngIf="myIndex<2"
            >
 
                {{"index is"+myIndex+" value is"+tmp}}
 
            </li>
            </ng-container>
        </ul>
        <p *ngIf="isMember">仅会员可见</p>
    `
})
 
export class Demo03Component{
    /*
         ts 指定数据类型
         count:number = 1
         hasMore:boolean = true
    */
    list:Array<any>=[100,200,300];
    isMember:boolean = true;
    
 
}
 
 
 
 
demo04_lianxi
<wiz_code_mirror>
 
 
 
 
 
import {Component} from '@angular/core'
 
@Component({
    selector:'demo04',
    template:`
        <h1>学生数组的练习</h1>
        <table>
            <thead>
              <tr>
               <th>年龄</th>
               <th>性别</th>
               <th>成绩</th>
              </tr>
            </thead>
        <tbody>
            <ng-container 
             *ngFor="let stu of stuList">
                <tr
                *ngIf="stu.score > 80">
                    <td>{{stu.age}}</td>
                    <td>{{stu.sex}}</td>
                    <td>{{stu.score}}</td>
                </tr>
            </ng-container>
        </tbody>
        </table>   
    `
})
 
export class Demo04Component{
    stuList:Array<any> = [
        {age:20,sex:1,score:85},
        {age:30,sex:1,score:70},
        {age:19,sex:1,score:86},
        {age:21,sex:1,score:90},
        {age:22,sex:1,score:30}
    ];
}
 
 
 
demo05_directive
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
 
@Component({
    selector: 'demo05',
    templateUrl: './demo05.component.html'
})
 
export class Demo05Component implements OnInit {
    answer:string='a';
    imgName:string='1.jpg';
    uName:string="zhangsan";
 
    //构造函数 简单的数据初始化
    constructor() { 
        console.log('在构造函数中...');
    }
 
    //复杂的数据初始化
    ngOnInit() {
        console.log('组件正在初始化');
     }
 
    //按钮按下时处理函数
    handleClick(){
        console.log('按钮被按下了');
    }
 
    //当双向数据绑定的数据发生变化时
    handleModelChange(msg:any){
        console.log(msg)
        console.log(this.uName);
    }
}
 
 
 
<wiz_code_mirror>
 
 
 
 
 
<h1>It is a test</h1>
 
<!--多重分支判断指令-->
<div [ngSwitch]="answer">
    <p *ngSwitchCase="'a'">A</p>
    <p *ngSwitchCase="'b'">B</p>
    <p *ngSwitchCase="'c'">C</p>
    <p *ngSwitchCase="'d'">D</p>
    <p *ngSwitchDefault>
        请输入正确的选项
    </p>
</div>
 
<!--属性绑定-->
<img 
src="../../img/1.jpg" alt="">
 
<img [src]="'../../img/'+imgName" alt="">
 
<!--事件绑定-->
<button (click)='handleClick()'>
    clickMe
</button>
 
<!--双向数据绑定-->
<input 
type="text" 
[(ngModel)]="uName"
(ngModelChange)="handleModelChange($event)"
/>
 
 
 
demo06_custom_directive
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
 
@Component({
    selector: 'demo06',
    template: '<h1 test="123">这是自定义指令demo</h1>'
})
 
export class Demo06Component implements OnInit {
    constructor() { }
 
    ngOnInit() { }
}
 
 
 
<wiz_code_mirror>
 
 
 
 
 
// a-directive
 
import { Directive,ElementRef,Input,OnInit} from '@angular/core';
 
@Directive({ selector: '[test]' })
export class TestDirective implements OnInit
{
    //@Input() test="";
    @Input('test') myTest="";
 
    constructor(private el:ElementRef) { 
        console.log('自定义指令被调用了');
        console.log(el);
        // console.log(this.test);
    }
    //初始化时 会自动调用的一个方法
    ngOnInit(){
        //将调用指令的元素 背景色设置一下
        this.el.nativeElement.style.backgroundColor = '#ff0000'
        // console.log(this.test);
        console.log(this.myTest);
    }
}
 
 
 
 
 
demo07_communication
 
xiaotou
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
 
@Component({
    selector: 'xiaotou',
    template: `
        <h1>这是父组件</h1>
        <datou 
        (toFatherEvent)="rcvMsg($event)"
        [myValue]="treasure">
        <datou>
    `
})
 
export class XiaoTouComponent implements OnInit {
    treasure:string = "传家宝";
    constructor() { }
 
    ngOnInit() { }
 
    rcvMsg(msg:any){
        console.log('儿子传来的信息是'+msg);
    }
}
 
 
 
datou
<wiz_code_mirror>
 
 
 
 
 
import { Component,Input,Output,EventEmitter, OnInit } from '@angular/core';
 
@Component({
    selector: 'datou',
    template: `
        <h3>这是子组件</h3>
        <p>{{"父组件传来的值"+myValue}}</p>
        <button (click)="askFather()">
            问候
        </button>
    `
})
export class DaTouComponent implements OnInit {
    // 通过Input指定可以接收哪些属性??
    @Input() myValue:any="";
 
    // 通过Output指定一个事件触发器
    @Output() toFatherEvent = 
        new EventEmitter();
 
    constructor() { }
 
    ngOnInit() { }
    //与父组件的通信:‘什么传家宝?是钱吗’
    askFather(){
        this.toFatherEvent
            .emit('什么传家宝?是钱吗');
    }
}
 
 
 
通过ViewChild来实现类似ref的效果:
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit,ViewChild } from '@angular/core';
 
 
@Component({
    selector: 'demo24',
    template: `
        <h1>hello demo24</h1>
        <demo24Son #sonCom></demo24Son>   
    `
})
 
export class Demo24Component implements OnInit {
    @ViewChild('sonCom') son:any;
    constructor() { }
 
    ngOnInit() { 
        console.log(this.son);
    }
}
 
 
 
通过服务来实现通信:
父组件
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit,ViewChild } from '@angular/core';
import {Demo24Service} from './demo24.service'
 
@Component({
    selector: 'demo24',
    providers:[Demo24Service],
    template: `
        <h1>hello demo24</h1>
        <button (click)="save()">save</button>
        <demo24Son #sonCom></demo24Son>   
    `
})
 
export class Demo24Component implements OnInit {
    @ViewChild('sonCom') son:any;
    constructor(private service:Demo24Service) { }
    save(){
        this.service.list.push(Math.random()*100)
    }
    ngOnInit() { 
        console.log(this.son);
    }
}
 
 
 
子组件
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
import {Demo24Service} from './demo24.service'
@Component({
    selector: 'demo24Son',
    template: `
        <h1>hello demo24Son</h1>
        <button (click)="getMsg()">get</button>
    `
})
 
export class Demo24SonComponent implements OnInit {
    name="zhangsna";
    constructor(private service:Demo24Service) { }
 
    getMsg(){
        console.log(this.service);
    }
 
    ngOnInit() { }
}
 
 
 
 
demo08_lianxi
聊天室、用户
 
聊天室
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
 
@Component({
    selector: 'chatroom',
    template: `
        <ul>
            <li 
            *ngFor="let tmp of list">
                {{tmp}}
            </li>
        </ul>
        <user 
         (addEvent)="rcvMsg($event)"
         uname="lucy"></user>
        <user 
         (addEvent)="rcvMsg($event)"
         uname="mike"></user>
    `
})
 
export class ChatRoomComponent implements OnInit {
    list:Array<any>=[];
    constructor() { }
 
    ngOnInit() { }
    //定义一个带有参数的方法
    rcvMsg(msg:string){
        console.log('父组件接收到的数据是'+msg);
        this.list.push(msg);
    }
 
}
 
 
 
 
用户
<wiz_code_mirror>
 
 
 
 
 
import { Component,Input,Output,EventEmitter, OnInit } from '@angular/core';
 
@Component({
    selector: 'user',
    template: `
        <span>{{uname+":"}}</span>
        <input type="text"
             [(ngModel)]="userMsg"/> 
        <button 
        (click)="sendToChatroom()">发送</button>
        <br/>
    `
})
 
export class UserComponent implements OnInit {
    userMsg:string = "";
    @Input() uname="";
    @Output() addEvent = 
        new EventEmitter();
    constructor() { }
 
    ngOnInit() { }
    //发送消息给聊天室
    sendToChatroom(){
        //触发事件并发送数据
        //hello mike --> lucy:hello mike
        let msg = 
         this.uname+":"+this.userMsg
    
        this.addEvent
        .emit(msg);
        this.userMsg="";
 
    }
}
 
 
 
 
demo09_bind
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
 
@Component({
    selector: 'demo09',
    template: `
        <button
         [ngClass]="{myHightlight:true}">
            clickme
        </button>
        <h1 
        [ngStyle]="{opacity:myOpacityValue}">透明度是动态绑定过来的</h1>
    `,
    styleUrls:['./test.css']
})
 
export class Demo09Component implements OnInit {
    myOpacityValue =0.2;
    constructor() { }
 
    ngOnInit() { }
}
 
 
 
test.css
<wiz_code_mirror>
 
 
 
 
 
.myHightlight{
    color:blue
}
 
 
 
 
demo10_lianxi
 
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit,OnDestroy } from '@angular/core';
 
@Component({
    selector: 'demo10',
    template: `
        <h1 [ngStyle]="{opacity:myOpacityValue}">
            这是Demo10
        </h1>
    `
})
 
export class Demo10Component implements OnInit ,OnDestroy{
    //定义一个保存透明度数据的变量
    myOpacityValue=0;
    myTimer:any = null;
    constructor() { }
 
    ngOnInit() {
        //启动定时器 在定时器中修改一个变量
        this.myTimer = setInterval(()=>{
            this.myOpacityValue+=0.1;
            if(this.myOpacityValue>1){
                this.myOpacityValue = 0;
            }
        },300)
     }
 
    ngOnDestroy(){
        // 组件销毁时,应该在此处理函数中完成清理工作
        clearInterval(this.myTimer);
    }
 
}
 
 
 
 
 
demo11_pipe
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
 
@Component({
    selector: 'demo11',
    templateUrl: './demo11.component.html'
})
 
export class Demo11Component implements OnInit {
    stuName:string = "Wentworth Miller";
    nowDate = new Date();
    totalPrice = 123.456789;
    constructor() { }
 
    ngOnInit() { }
}
 
 
 
<wiz_code_mirror>
 
 
 
 
 
<h1> 这是一个和管道相关的demo </h1>
 
<!-- uppercase/lowercase -->
<p>{{stuName | uppercase}}</p>
<p>
    {{stuName | uppercase | lowercase }}
</p>
 
<!-- date -->
<p>{{nowDate}}</p>
<p>{{nowDate | date}}</p>
<!--需要在调用过滤器时指定参数-->
<p>{{nowDate | date:'MM-dd'}}</p>
 
<!-- number:'整数位保留最小位数.小数位保留最小位数-小数点保留最多位数' -->
<p>{{totalPrice}}</p>
<p>{{totalPrice | number:'4.2-4'}}</p>
 
<!-- slice:start:end裁剪数组或者字符串,并返回裁剪后的目标子集-->
<p>{{stuName | slice:4}}</p>
<p>{{stuName | slice:4:7}}</p>
 
<!--调用自定义的管道-->
<p>{{stuName | testNG:0}}</p>
 
<h2>{{0 | sex:'zh'}}</h2>
 
 
 
 
sex.pipe.ts
<wiz_code_mirror>
 
 
 
 
 
import { Pipe, PipeTransform } from '@angular/core';
 
@Pipe({
    name: 'sex'
})
 
export class SexPipe implements PipeTransform {
    /**
     *      0 | sex:'en' --》girl
            1 | sex:'en' --》boy
            0 | sex:'zh' --》女
            1 | sex:'zh' --》男
     */
    transform(value: any, ...args: any[]): any {
        if(args[0] == 'en'){
            if(value == 0){
                return 'girl'
            }
            else{
                return 'boy'
            }
        }else{
            if(value == 0){
                return '女'
            }
            else{
                return '男'
            }    
        }
    }
}
 
 
 
test.pipe.ts
<wiz_code_mirror>
 
 
 
 
 
// a-pipe
// a-component
// a-directive
// a-module
 
import { Pipe, PipeTransform } from '@angular/core';
 
@Pipe({
    name: 'testNG'
})
 
export class TestPipe implements PipeTransform {
    transform(value: any, ...args: any[]): any {
        let result ="";
        if(args[0] == 1){
            result = value.toUpperCase();
        }
        else{
            result = value.toLowerCase()
        }
        return result;
    }
}
 
 
 
 
demo12_service
 
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
import {UserService} from './user.service'
import {HeartBeatService} from './heartbeat.service'
 
// 如果用户已登录:下午好!
// 如果用户未登录:请去登录
@Component({
    selector: 'demo12',
    // providers:[UserService],
    template: `
        <h1>service example</h1>
        <p>
    {{isUserLogin?'下午好!':'请去登录'}}
        </p>
        <button (click)="start()">开始心跳</button>
        <button (click)="stop()">结束心跳</button>
    `
})
 
export class Demo12Component implements OnInit {
    isUserLogin:boolean = false;
    //在构造函数中完成服务类的实例化
    constructor(
        private myService:UserService,
        private myHBS:HeartBeatService) { }
 
    ngOnInit() {
        //希望在组件初始化之后,就去调用服务中的方法
        this.isUserLogin 
        = this.myService.checkUserLogin();
     }
 
     start(){
         this.myHBS.startHearBeat();
     };
     stop(){
         this.myHBS.stopHeartBeat();
     }
 
}
 
 
 
user.service.ts
<wiz_code_mirror>
 
 
 
 
 
// a-service
 
import { Injectable } from '@angular/core';
 
@Injectable()
export class UserService {
 
    constructor() { }
    //在服务中定义一个方法,用来检查用户是否登录
    checkUserLogin(){
        return true;
    }
}
 
 
 
heartbeat.service.ts
<wiz_code_mirror>
 
 
 
 
 
import { Injectable } from '@angular/core';
 
@Injectable()
export class HeartBeatService {
    myTimer:any = null;
    constructor() { }
 
    startHearBeat(){
        if(this.myTimer){
            return;
        }
        this.myTimer = 
        setInterval(()=>{
            console.log('in HeartBeat..');
        },500);
    }
 
    stopHeartBeat(){
        clearInterval(this.myTimer)
        this.myTimer = null;
    }
}
 
 
 
 
demo13_http
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
import {MyHttpService} from './myhttp.service'
 
@Component({
    selector: 'demo13',
    template: `
        <h2>http</h2>
        <button (click)="handleClick()">
            clickMe
        </button>
    `
})
 
export class Demo13Component implements OnInit {
    constructor(private myHS:MyHttpService) { }
 
    ngOnInit() { }
 
    handleClick(){
        //从服务器端获取数据
        this.myHS.sendRequest("http://localhost/admin/data/product_list.php")
        .subscribe((result)=>{
            console.log(result);
        })
    }
}
 
 
 
myhttp.service.ts
<wiz_code_mirror>
 
 
 
 
 
// a-service-http
 
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
 
@Injectable()
export class MyHttpService {
    constructor(private http: Http) { }
 
    sendRequest(myUrl:string){
        // a-http-get
        return this.http.get(
            myUrl
            )
            .map((response: Response) => response.json());
    }
    
}
 
 
 
 
demo14_lianxi
<wiz_code_mirror>
 
 
 
 
 
import { Component, OnInit } from '@angular/core';
import {StoreHttpService} from './storehttp.service'
 
@Component({
    selector: 'demo14',
    template: `
        <button (click)="loadData()">
            clickme
        </button>
        <ul>
            <li *ngFor="let tmp of list">
                {{tmp.title}}
            </li>
        </ul>
    `
})
 
export class Demo14Component implements OnInit {
 
    //定义一个数组,保存result.data中的数据
    list:Array<any> = [];
 
    constructor(private myHS:StoreHttpService) { }
 
    ngOnInit() { }
 
    loadData(){
        this.myHS.sendGet('http://localhost/admin/data/product_list.php')
        .subscribe((result)=>{
            this.list = result.data;
        })
    }
}
 
 
 
 
storehttp.service.ts
<wiz_code_mirror>
 
 
 
 
 
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
 
@Injectable()
export class StoreHttpService {
    constructor(private http: Http) { }
 
    sendGet(myUrl:string){
        // a-http-get
        return this.http.get(myUrl)
            .map((response: Response) => response.json());
    }
    
}
posted @ 2023-06-26 19:04  kunyashaw  阅读(4)  评论(0编辑  收藏  举报
回到顶部