6.20 - Angular 2 学习笔记(一)

查看原文:http://note.youdao.com/noteshare?id=378c6e7137d4e384aef9395254e36bb3&sub=350CA885408046379F60DECEE53529BB

 

一.安装

安装脚手架:
	npm install @angular/cli –g
运行项目创建向导
	ng new hello-world --skip-xxx
创建第一个组件
	ng g component prod-list --force --routing
	ng g component prodList

 

二.组件

2.1 创建组件

ng generate component hello-world

 

2.2 最基本的组件包括2部分:

Component注解

定义组件的类

// 从angular/core模块中导入我们用到的模块 Component OnInit[两个TS对象] 
import { Component, OnInit } from '@angular/core';

// 注解 让编译器给被注解的代码添加特定的功能
// Component 注解就将此类 标注成了一个组件

// selector:定义HTML中的标签   <app-hello-world></app-hello-world>

// templateUrl:指定从哪个文件加载该模板,当加载该组件的时候,
//就会读取指定的文件内容作为组件的模板
// 也可以使用 template 直接传入模板 
//@Component({
//selector: 'app-hello-world',
//    template: `
//    <p>
//    hello-world works inline!
//    </p>
//    `
//})

// styleUrls : 加载该组件的样式css, 组件指定的样式仅仅作用于组件本身
// 并且参数时候数组,意味着可以添加多个样式
@Component({
    selector: 'app-hello-world',
    templateUrl: './hello-world.component.html',
    styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {
    constructor() { }
    ngOnInit() {
    }
}

 

2.3 加载组件

在 code/first_app/angular2_hello_world/src/app/app.component.html 中加载组件app-hello-world

<h1> {{title}} <app-hello-world></app-hello-world> </h1>

 

2.4 组件添加数据

export class UserItemComponent implements OnInit {
    name: string; // <-- added name property
    constructor() {
        this.name = 'Felipe'; // set the name
    }
    ngOnInit() {
    }
}

// 使用{{  name }}  双花括号 模板语法。括号中的任何东西都会被当成一个表达式
<p>
Hello {{ name }}
</p>

 

2.5 使用数组,为一组对象反复的渲染同样的页面脚本

export class UserListComponent implements OnInit { names: string[]; constructor() { this.names = ['Ari', 'Carlos', 'Felipe', 'Nate']; } ngOnInit() { } } // 在一个列表上进行迭代,为每个条目生成一个新的标签 // let name of names -- 表示循环处理names,并将值赋值给name变量 <ul> <li *ngFor="let name of names">Hello {{ name }}</li> </ul>

 

2.6 在组件中使用其他组件,在user-list中使用user-item,并传值

<ul> <app-user-item *ngFor="let name of names"> </app-user-item> </ul>

 

2.7 组件间传值

import {
  Component,
  OnInit,
  Input   // 导入input
} from '@angular/core';

@Component({
  selector: 'app-user-item',
  templateUrl: './user-item.component.html',
  styleUrls: ['./user-item.component.css']
})
export class UserItemComponent implements OnInit {

  // 增加 input注解, 从父模板中接收name 的值
  @Input()
  name:string;  // 增加名称属性

  constructor() {
    //this.name = "Pipe";
  }

  ngOnInit() {
  }

}

 

2.8 使用【】传入Input的值

[foo] 意味着将 父组件foo的值赋值给子组件同名变量foo

<ul> <app-user-item *ngFor="let name of names" [name] = "name"> </app-user-item> </ul>

 

2.9 ng serve 启动命令

大体启动过程如下

1.ng 查阅angular-cli.json 指定一个‘main’文件,这里是main.ts

2.main.ts是应用的入口点,负责引导加载我们的应用。 过程中会引导一个AppModule,AppModule在app.module.ts文件中指定

3.AppModule 中 指定@ngModule, 其中指定了各种组件,以及顶层组件AppComponent

4.AppComponent 的 html中引用 <app-user-list> 标签,渲染出我们的列表

 

2.10 @ngModule

@ngModule 标注后面的这段代码是什么类型的元数据,包括三个属性

declarations 、 imports 、 bootstrap

 

1.declarations

定义在该模块中使用的组件。即:要想在模块中使用组件,首先在ngModule中声明

 

2.imports

描述该模块有那些依赖

 

3.bootstrap

模块引导中,指定哪个模块在顶层

 

2.11 元数据

名称

类型

作用

selector

string

自定义组件的标签,用于匹配元素。

inputs

string[]

指定组件的输入属性。

outputs

string[]

指定组件的输出属性

host

{[key:string],string}

指定指令或组件的事件,动作和属性等

providers

any[]

指定该组件及其所有子组件(含ContentChildren)可用的服务依赖注入

exportAs

string

给指令分配一个变量,使其可以在模板中使用

moduleId

string

包含该组件模块的id,他被用于解析模板和样式的相对路径

queries

{[key:string],any}

设置需要被注入到组件的查询

viewProviders

any[]

指定该组件及其所有子组件可用的服务

changeDetection

ChangeDetectionStrategy

指定使用的变化监测策略

templateUrl

string

模板路径

styleUrls

string[]

样式路径

template

string

内联模板

styles

string[]

内联样式

animations

AnimationEntryMetadata[]

angular动画

encapsulation

ViewEncapsulation

设置组件的试图包装选项

interpolation

[string,string]

设置自定义插值标记,默认是{{}}

 

三、输入框、按钮、事件

【code/first_app/angular2_reddit/src/app/app.component.html】
// (click) 圆括号中添加事件
// <button (click)="addArticle()"> 点击按钮,调用addArticle中的方法
// 在 AppComponent 类中定义这个函数
// input 后面使用#(hash)来标识将标签的值赋值给#变量,整个页面都可以使用

<form class="ui large form segment">
  <h3 class="ui header">Add a Link</h3>
  <div class="field">
    <label >Title:</label>
    <input name="title" #newtitle>
  </div>
  <div class="field">
    <label >Link:</label>
    <input name="link" #newlink>
  </div>
  <button (click)="addArticle(newtitle, newlink)" class="ui positive right floated button">
      Submit link
  </button>
</form>


【code/first_app/angular2_reddit/src/app/app.component.ts】
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hello-reddit';

  addArticle(title: HTMLInputElement, link: HTMLInputElement): boolean {
    console.log(`Adding article title: ${title.value} and link: ${link.value}`);
    return false;
  }

}

/----------  注  --------**/
1.绑定input的值
    <input name="title" #newtitle>
    将<input>绑定到变量 newtitle上, newtitle 相当于一个HTMLInputElement
    可以通过 newtitle.value 获取值

2.将事件绑定到动作
    button 添加了事件(click)
    当事件发生(点击)时,会调用addArticle,并传入参数newtitle, newlink
    click事件返回值:true 会刷新。false 不会刷新

3.定义逻辑操作
    在AppCompent中,定义方法addArticle,并接受两个参数
    参数的类型是HTMLInputElement
    函数中要想使用参数的值,应该打点value使用
    
4.使用标签
    如果想在AppComponent中想使用<Article>标签,那么需在App.Module的declarations的列表中  

 

 

四、类封装、集合、遍历循环、排序

/----------  类封装  --------**/
// -- 正确的思想是将完整的数据结构,抽离出来。形成一个数据结构 -- 类
// -- 其实也就是MVC中的Model
export class Article {
  title: string;
  link: string;
  votes: number;
  constructor(title: string, link: string, votes?: number) {
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }

  voteUp(): void {
    this.votes += 1;
  }
  voteDown(): void {
    this.votes -= 1;
  }
}


/----------  集合  --------**/
export class AppComponent {
  title = 'hello-reddit';

  articles:Article[];

  constructor(){
    this.articles = [
      new Article('111','http://111',1),
      new Article('222','http://222',2),
      new Article('333','http://333',3)
    ];
  }

// 集合中添加元素  push
  addArticle(title: HTMLInputElement, link: HTMLInputElement): boolean {
    console.log(`Adding article title: ${title.value} and link: ${link.value}`);
    this.articles.push(new Article(title.value,link.value,0));
    title.value = '';
    link.value = '';
    return false;
  }

}


/----------  遍历  --------**/
<div class="ui grid posts">
  <app-article
    *ngFor="let foobar of articles"
    [article]="foobar">
  </app-article>
</div>


/----------  排序  --------**/
sortedArticles(): Article[] {
    return this.articles.sort((a: Article, b: Article) => b.votes - a.votes);
}

<app-article
  *ngFor="let foobar of sortedArticles()"
  [article]="foobar">
</app-article>



/----------  注  --------**/
1.组件的复用[组件作为参数,传递给组件,进行组件的复用]
class ArticleComponent {
    @Input() article: Article;
    // ...
    
2.使用[变量] 的方式,将变量的值传递给html元素
    -- 将变量myArticle的值,传递给属性名为article的属性
    <app-article [article]="myArticle"></app-article>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值