Angular 4 基础教程
目录
第一节 - 基于 Angular CLI 新建项目安装 Angular CLI (可选)
$ npm install -g @angular/cli
$ ng --version 使用 Angular CLI
$ ng new angular4-fundamentals
$ ng serve 若想进一步了解 Angular CLI 的详细信息,请参考 Angular CLI 终极指南。 第二节 - 创建简单的组件新建组件$ ng generate component simple-form --inline-template --inline-style # Or $ ng g c simple-form -it -is # 表示新建组件,该组件使用内联模板和内联样式 在命令行窗口运行以上命令后,将输出以下内容: installing component create src/app/simple-form/simple-form.component.spec.ts create src/app/simple-form/simple-form.component.ts update src/app/app.module.ts 即执行上述操作后,创建了两个文件:
除此之外, @NgModule({ declarations: [ AppComponent,SimpleFormComponent ],... }) export class AppModule { } 使用组件AppComponentimport { Component } from '@angular/core'; @Component({ selector: 'app-root',template: ` <h3>{{title}}</h3> <div> <app-simple-form></app-simple-form> </div> ` }) export class AppComponent { title = 'Hello,Angular'; } SimpleFormComponentimport { Component,OnInit } from '@angular/core'; @Component({ selector: 'app-simple-form',template: ` <p> simple-form Works! </p> `,styles: [] }) export class SimpleFormComponent implements OnInit { constructor() { } ngOnInit() { } } 从生成的 $ ng g c simple-form -it -is 即 Angular CLI 在创建组件时,自动帮我们添加了前缀。那为什么前缀是 { ... "apps": [ { "root": "src","outDir": "dist",... "prefix": "app",... } ],} 当然你可以根据实际需求,自行更改默认的前缀配置。 第三节 - 事件和模板引用在 Angular 中,我们可以使用 SimpleFormComponentimport {Component,OnInit} from '@angular/core'; @Component({ selector: 'app-simple-form',template: ` <div> <input #myInput type="text"> <button (click)="onClick(myInput.value)">点击</button> </div> `,styles: [] }) export class SimpleFormComponent implements OnInit { onClick(value) { console.log(value); } ngOnInit() {} } 需要注意的是,若我们改变绑定的表达式为 <input type="text"> 通过该输出结果,我们可以知道 第四节 - 事件进阶获取鼠标事件在第三节的示例中,假如我们需要获取鼠标事件,那应该怎么办呢?这时,我们可以引入 import {Component,template: ` <div> <input #myInput type="text"> <button (click)="onClick($event,myInput.value)">点击</button> </div> `,styles: [] }) export class SimpleFormComponent implements OnInit { onClick(event,value) { console.log(event); console.log(value); } ngOnInit() {} } 成功运行以上代码,当我们点击按钮时,控制台将输出: MouseEvent {isTrusted: true,screenX: 180,screenY: 207,clientX: 165,clientY: 75…} 需要注意的是,参数名一定要使用 <button (click)="onClick(myInput.value,$event)">点击</button> 当 Angular 在调用我们的事件处理函数时,会自动帮我们处理调用的参数。 获取键盘事件import {Component,template: ` <div> <input #myInput type="text" (keydown.enter)="onEnter($event,myInput.value)"> <button (click)="onClick($event,styles: [] }) export class SimpleFormComponent implements OnInit { // ... onEnter(event,value) { console.log(event); console.log(value); } } 以上代码中, 第五节 - 注入服务新建服务$ ng g s mail 在命令行窗口运行以上命令后,将输出以下内容: installing service create src/app/mail.service.spec.ts create src/app/mail.service.ts WARNING Service is generated but not provided,it must be provided to be used 即执行上述操作后,创建了两个文件:
除此之外, 配置服务import {MailService} from "./mail.service"; @NgModule({ ... providers: [MailService],bootstrap: [AppComponent] }) export class AppModule { } 更新服务import { Injectable } from '@angular/core'; @Injectable() export class MailService { message: string ='该消息来自MailService'; constructor() { } } 使用服务import { Component } from '@angular/core'; import {MailService} from "./mail.service"; @Component({ selector: 'app-root',template: ` <h3>{{title}}</h3> <div> <app-simple-form></app-simple-form> {{mailService.message}} </div> ` }) export class AppComponent { title = 'Hello,Angular'; constructor(private mailService: MailService) {} } 除了使用 import {Component,Inject} from '@angular/core'; @Component({...}) export class AppComponent { title = 'Hello,Angular'; constructor(@Inject(MailService) private mailService) {} } 不过对于 使用Inject装饰器AppModule@NgModule({ ... providers: [ MailService,{provide: 'apiUrl',useValue: 'https://jsonplaceholder.typicode.com/'} ],bootstrap: [AppComponent] }) export class AppModule { } AppComponent@Component({ selector: 'app-root',template: ` <h3>{{title}}</h3> <div> <app-simple-form></app-simple-form> {{mailService.message}} <p>API_URL: {{apiUrl}}</p> </div> ` }) export class AppComponent { title = 'Hello,Angular'; constructor( @Inject(MailService) private mailService,@Inject('apiUrl') private apiUrl ) {} } 第六节 - 使用 ngFor 指令在 Angular 中我们可以使用 使用 ngFor 指令更新 MailService 服务import { Injectable } from '@angular/core'; @Injectable() export class MailService { messages: string[] = [ '天之骄子,加入修仙之路群','Shadows,加入修仙之路群','Keriy,加入修仙之路群' ]; } 更新 AppComponent 组件import {Component} from '@angular/core'; import {MailService} from "./mail.service"; @Component({ selector: 'app-root',template: ` <h3>{{title}}</h3> <ul> <li *ngFor="let message of mailService.messages; index as i;"> {{i}} - {{message}} </li> </ul> ` }) export class AppComponent { title = 'Hello,Angular'; constructor(private mailService: MailService) {} } 在 AppComponent 组件的模板中,我们使用
需要注意的是, <ng-template ngFor let-item [ngForOf]="items" let-i="index"> <li>...</li> </ng-template> 除了 第七节 - 使用 Input 装饰器为了让我们能够开发更灵活的组件,Angular 为我们提供了 使用 Input 装饰器更新 SimpleFormComponent 组件import {Component,OnInit,Input} from '@angular/core'; @Component({ selector: 'app-simple-form',template: ` <div> {{message}} <input #myInput type="text" (keydown.enter)="onEnter($event,styles: [] }) export class SimpleFormComponent implements OnInit { @Input() message: string; // ... } 更新 AppComponent 组件import {Component} from '@angular/core'; import {MailService} from "./mail.service"; @Component({ selector: 'app-root',template: ` <h3>{{title}}</h3> <app-simple-form *ngFor="let message of mailService.messages;" [message]="message"> </app-simple-form> ` }) export class AppComponent { title = 'Hello,Angular'; constructor(private mailService: MailService) {} } 在 AppComponent 组件模板中,我们使用 需要注意的是,当 export class SimpleFormComponent implements OnInit { @Input('message') msg: string; // ... } 不过一般不推荐这样做,尽量保持名称一致。 第八节 - 使用双向绑定使用过 AngularJS 1.x 的同学,应该很熟悉 使用双向绑定引入 FormsModuleimport {FormsModule} from "@angular/forms"; @NgModule({ // ... imports: [ BrowserModule,FormsModule ],// ... }) export class AppModule { } 使用 ngModel 指令@Component({ selector: 'app-simple-form',template: ` <div> {{message}} <input #myInput type="text" [(ngModel)]="message"> <button (click)="onClick($event,styles: [] }) export class SimpleFormComponent implements OnInit { // ...} 上面示例中,我们使用
除了使用双向绑定,我们也可以通过 第九节 - 使用 Output 装饰器
在介绍 Output 属性装饰器前,我们先来介绍一下 let numberEmitter: EventEmitter<number> = new EventEmitter<number>(); numberEmitter.subscribe((value: number) => console.log(value)); numberEmitter.emit(10); 接下来我们来介绍如何使用 使用 Output 装饰器更新 SimpleFormComponent 组件import {Component,Input,Output,EventEmitter} from '@angular/core'; @Component({ selector: 'app-simple-form',template: ` <div> {{message}} <input #myInput type="text" [(ngModel)]="message"> <button (click)="update.emit({text: message})">更新</button> </div> `,styles: [] }) export class SimpleFormComponent implements OnInit { @Input() message: string; @Output() update = new EventEmitter<{text: string}>(); ngOnInit() { } } 更新 MailService 服务import {Injectable} from '@angular/core'; @Injectable() export class MailService { messages: Array<{id: number,text: string}> = [ {id: 0,text: '天之骄子,加入修仙之路群'},{id: 1,text: 'Shadows,加入修仙之路群'},{id: 2,text: 'Keriy,加入修仙之路群'} ]; update(id,text) { this.messages = this.messages.map(msg => { return msg.id === id ? {id,text} : msg; }); } } 更新 AppComponent 组件import {Component} from '@angular/core'; import {MailService} from "./mail.service"; @Component({ selector: 'app-root',template: ` <h3>{{title}}</h3> <ul> <li *ngFor="let message of mailService.messages;"> {{message.text}} </li> </ul> <app-simple-form *ngFor="let message of mailService.messages;" [message]="message.text" (update)="onUpdate(message.id,$event.text)"> </app-simple-form> ` }) export class AppComponent { title = 'Hello,Angular'; onUpdate(id,text) { this.mailService.update(id,text); } constructor(private mailService: MailService) {} } 上面示例中,我们仍然使用 第十节 - 组件样式在 Angular 中,我们可以在设置组件元数据时通过 使用 styles 属性import {Component,template: ` ... `,styles: [` :host { margin: 10px; } input:focus { font-weight: bold;} ` ] }) export class SimpleFormComponent implements OnInit { @Input() message: string; @Output() update = new EventEmitter<{text: string}>(); ngOnInit() {} } 上面示例中 用过 AngularJS 1.x 的同学,对 使用 ngClass 指令
@Component({ selector: 'app-simple-form',template: ` <div> {{message}} <input #myInput type="text" [(ngModel)]="message" [ngClass]="{mousedown: isMousedown}" (mousedown)="isMousedown = true" (mouseup)="isMousedown = false" (mouseleave)="isMousedown = false" > <button (click)="update.emit({text: message})">更新</button> </div> `,styles: [` :host { margin: 10px; } .mousedown { border: 2px solid green; } input:focus { font-weight: bold; outline: none;} ` ] }) export class SimpleFormComponent implements OnInit { isMousedown: boolean; // ... } ngClass 指令用法<!-- 使用布尔值 --> <div [ngClass]="{bordered: false}">This is never bordered</div> <div [ngClass]="{bordered: true}">This is always bordered</div> <!-- 使用组件实例的属性 --> <div [ngClass]="{bordered: isBordered}"> Using object literal. Border {{ isBordered ? "ON" : "OFF" }} </div> <!-- 样式名包含'-' --> <div[ngClass]="{'bordered-box': false}"> Class names contains dashes must use single quote </div> <!-- 使用样式列表 --> <div class="base" [ngClass]="['blue','round']"> This will always have a blue background and round corners </div> 除了 使用 ngStyle 指令
ngStyle 指令用法<div [ngStyle]="{color: 'white','background-color': 'blue'}"> Uses fixed white text on blue background </div> 需要注意的是, 对于一些场合,我们也可以直接利用 Angular 属性绑定的语法,来快速设置元素的样式。
<div [style.background-color="'yellow'"]> Use fixed yellow background </div>
<!-- 支持单位: px | em | %--> <div> <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize"> Red Text </span> </div> 我有话说应该如何引入第三方 UI 库,如 bootstrap若要引入第三方 UI 库,可以在 { "apps": { "styles": [ "styles.css","../node_modules/bootstrap/dist/css/bootstrap.min.css" ] } } 除了本系列教程外,还有其它入门的资料么?本系列教程的主要目的是让初学者对 Angular 的相关基础知识,有一定的了解。除了本系列教程外,初学者还可以参考以下教程:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |