Angular快速入门
一、 插值表达式
在 Angular 中,我们可以使用 {{}} 插值语法实现数据绑定。
1. 绑定普通文本
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>`,
})
export class AppComponent {
name = 'Angular';
}
2. 绑定对象属性
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h2>大家好,我是{{name}}</h2>
<p>我来自<strong>{{address.province}}</strong>省,
<strong>{{address.city}}</strong>市
</p>
`,
})
export class AppComponent {
name = 'Semlinker';
address = {
province: '福建',
city: '厦门'
}
}
3. 值得一提的是,我们可以使用 Angular 内置的 json 管道,来显示对象信息,管道用来格式化数据。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div>
<p>大家好我是来自{{address.province}}省{{address.city}}市的{{name}}</p>
<p>{{address | json}}<p>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
address = {
province:'河北',
city: '唐山'
};
}
二、 组件
在 Angular 中,我们可以通过 @Component 装饰器和自定义组件类来创建自定义组件。
1. 在 Angular 中,我们可以使用 @Component 装饰器来定义组件的元信息
@Component({
selector: 'my-app', // 用于定义组件在HTML代码中匹配的标签
template: `<h1>Hello {{name}}</h1>`, // 定义组件内嵌视图
})
2. 定义组件类
export class AppComponent {
name = 'Angular';
}
3. 定义数据接口
在 TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。
interface Person {
name: string;
age: number;
}
let semlinker: Person = {
name: 'semlinker',
age: 31
};
三、 自定义组件示例:创建 UserComponent 组件
1. 在WebStrom的Terminal中使用ng g component user命令创建一个UserComponent组件。
以上是我们使用angular-cli工具自动为我们生成的代码。
2. 修改User组件和模板内容,在构造函数中初始化用户信息。
使用插值表达式将组件类(控制器)中的属性显示在模板中
3. 在App主组件中使用自定义的User组件
四、 常用指令简介
在 Angular 实际项目中,最常用的指令是 ngIf 和 ngFor 指令。
1. ngIf 指令
该指令用于根据表达式的值,动态控制模板内容的显示与隐藏。它与 AngularJS 1.x 中的 ng-if 指令的功能是等价的。
ngIf 指令语法如下
<div *ngIf="condition">...</div>
2. ngFor 指令
该指令用于基于可迭代对象中的每一项创建相应的模板。它与 AngularJS 1.x 中的 ng-repeat 指令的功能是等价的。
ngFor 指令语法
<li *ngFor="let item of items;">...</li>
3. ngIf 与 ngFor 指令使用示例
五、 事件绑定
在 Angular 中,我们可以通过 (eventName) 的语法,实现事件绑定。
1. 事件绑定语法
<date-picker (dateChanged)="statement()"></date-picker>
等价于
<date-picker on-dateChanged="statement()"></date-picker>
2. 介绍完事件绑定的语法,接下来我们来为 UserComponent 组件,开发一个功能,即可以让用户动态控制技能信息的显示与隐藏。
六、 补充:如何配置WebStorm,让其支持断点调试
1. 给Chrome安装插件JetBrains IDE Support。
此处需要翻墙才能访问。
安装成功后,右键选择JB图标,选择“选项”进入设置。
2. 接下来设置默认浏览器为Chrome这一步很关键,因为调试的浏览器只会启动默认浏览器。
3. 在WebStorm的TypeScript脚本上设置断点。
4. 右键选择index.html,选择调试index.html
5. 修改WebStorm调试配置,将http://localhost:63342/mingxun/src/index.html的网址改成http://localhost:4200,然后选择调试运行
则会进入WebStorm中的断点了。
七、 Angular表单简介
Angular 中有两种表单:
Ø Template Driven Forms - 模板驱动式表单 (类似于 AngularJS 1.x 中的表单 )
Ø Reactive Forms - 响应式表单
这里主要介绍模板驱动式的表单,接下来我们来演示如何通过表单来为我们的之前创建的 UserComponent 组件,增加让用户自定义技能的功能。
1. 在AppModule主模块中导入表单模块,在主模块中引入表单模块之后,在其他各组件中就可以直接使用表单了。
响应式表单咱们放在后面讲,这里的模板驱动式表单也只是介绍了一下,体验一下。
关于其他概念我们分别放入单独的专题中去讲。