• Angular中的数据绑定分以下几种:

    • HTML绑定:{{ng表达式}}
    • 属性绑定
    • 指令绑定
    • 事件绑定
    • 双向数据绑定

      1、HTML绑定

  • 使用{{ng表达式}}进行绑定 ```typescript import { Component, OnInit } from ‘@angular/core’;

@Component({ selector: ‘app-my-com03’, templateUrl: ‘./my-com03.component.html’, styleUrls: [‘./my-com03.component.css’] }) export class MyCom03Component { name = ‘Jack’; age = 20; }

  1. ```html
  2. ======my-com03.component.html========
  3. <h1>name: {{name}}</h1>
  4. <h1>age: {{age}}</h1>
  5. ======app.component.html=========
  6. <app-my-com03></app-my-com03>

image.png

  • ng表达式支持类型 | 比较运算符({{a < 20}}) | true | | —- | —- | | 逻辑运算符({{a > 20 && a < 40}}) | true | | 调用方法({{a.toUpperCase()}}) | true | | 获取数组下标({{a[1]}}) | true | | 三目运算符({{a < 20 ? fun1() : fun2()}}) | true | | 调用属性({{a.length}}) | true | | new操作({{new Obj()}}) | false | | JSON序列化({{JSON.stringfy}}) | false |

2、属性绑定

  • angular中实现属性绑定有两种方式:

    • 使用{{}}对属性进行绑定

      1. ======my-com03.component.html========
      2. <span title="{{name}}">bindName</span>

      image.png

    • 使用[prop]="参数"实现属性绑定

      1. ======my-com03.component.html========
      2. <span [title]="age">bindAge</span>

      image.png

3、事件绑定

  • angular中的事件绑定语法:(事件名)="方法名(args)"
    1. ======my-com03.component.html========
    2. <button (click)="printName()">Name</button>
    image.png

4、指令绑定

4.1、Angular指令系统

  • 下列例子中:省略了在app.component.html引用组件的代码,和组件注册代码

    循环绑定*ngFor

  • 语法规则

    1. <div *ngFor="let item of items">{{item.name}}</div>
  • 定义的临时变量名必须使用let声明;如果要使用循环的下标,需要传参操作如下例

    1. ============ng-for-component.component.html===========
    2. <ul>
    3. <li *ngFor = "let stu of stuList; index as i">{{i}}:{{stu.name}}</li>
    4. </ul>

    ```typescript =============ng-for-component.component.ts=========== @Component({ selector: ‘app-ng-for-component’, templateUrl: ‘./ng-for-component.component.html’, styleUrls: [‘./ng-for-component.component.css’] }) export class NgForComponentComponent { stuList = [ {name: ‘mike’}, {name: ‘jack’}, {name: ‘joe’}, {name: ‘july’} ];

}

  1. - 再根视图中引用新的组件观察输出结果
  2. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/12407770/1644483949393-cb5b3083-ae7f-4961-bc63-bd6719e70637.png#clientId=u40b766af-1a2f-4&from=paste&height=161&id=u6055d50c&margin=%5Bobject%20Object%5D&name=image.png&originHeight=484&originWidth=1221&originalType=binary&ratio=1&size=41017&status=done&style=shadow&taskId=u6f7f9813-396a-45ce-8c2b-59e7bda699b&width=407)
  3. <a name="Ag1Uw"></a>
  4. ### *ngif指令
  5. - `*ngIf="布尔表达式"`
  6. - `NgIf`指令的主要作用时应用于宿主元素,来决定`DOM`树中是否存在宿主元素及其子元素
  7. ```typescript
  8. @Component({
  9. selector: 'app-ng-if-component',
  10. templateUrl: './ng-if-component.component.html',
  11. styleUrls: ['./ng-if-component.component.css']
  12. })
  13. export class NgForComponentComponent {
  14. age = 10;
  15. isVip = true;
  16. isSVip = false;
  17. }
  1. <div *ngIf="isVip">
  2. <h1>好康的!!!</h1>
  3. </div>
  4. <div *ngIf="isSVip">
  5. <h1>超级好康的!!!</h1>
  6. </div>
  • 显示结果如下:

image.png

  • 查看页面元素可以看到,*ngIf参数为false的宿主元素及其子元素会被删除

    1. <app-ng-if-component _ngcontent-vio-c12="" _nghost-vio-c11="">
    2. <div _ngcontent-vio-c11="">
    3. <h1 _ngcontent-vio-c11="">好康的!!!</h1>
    4. </div>
    5. </app-ng-if-component>
  • *ngIf相对的else情况处理:*ngIf="condition; else Templatexxx" 需要结合ng-template元素使用

  • ng-template元素定义了一个默认情况下不渲染任何内容的模板,只有被引用后才会被渲染;ng-template使用#模板id的方式进行模板和引用的对应

    1. <div *ngIf="age >= 18; else healthTemplate">
    2. <h1>好康的!!!</h1>
    3. </div>
    4. <ng-template #healthTemplate>
    5. <h1>不要!!!</h1>
    6. </ng-template>
  • 结果:

image.png

*ngSwitch指令

  • 对于分支比较多的类型,再使用ngIf来判断比较麻烦,且代码不简洁,此时可以使用ngSwitch
  • ngSwitchngSwitchCalsengSwitchDefault,一起使用可以处理多种分支情况

    1. ==========ng-switch-com.component.ts=========
    2. @Component({
    3. selector: 'app-ng-switch-com',
    4. templateUrl: './ng-switch-com.component.html',
    5. styleUrls: ['./ng-switch-com.component.css']
    6. })
    7. export class NgSwitchComComponent {
    8. users = [
    9. {name: 'jack', city: "Shanghai"},
    10. {name: "joe", city: "Beijing"},
    11. {name: "july", city: "Wuhan"},
    12. {name: "mike", city: "GagaTun"}
    13. ]
    14. }
    1. =======ng-switch-com.component.html========
    2. <div *ngFor="let user of users">
    3. <div [ngSwitch]="user['city']">
    4. <h2 *ngSwitchCase="'Beijing'">北京汉英您</h2>
    5. <h2 *ngSwitchCase="'Shanghai'">上海欢迎您</h2>
    6. <h2 *ngSwitchCase="'Wuhan'">武汉欢迎您</h2>
    7. <h2 *ngSwitchDefault>没有对应的City</h2>
    8. </div>
    9. </div>
  • 显示效果

image.png

[ngStyle]样式指令

  • 使用ngStyle根据组件的不同状态设置多个内联样式
  • 语法规则:[ngStyle]="样式Obj"

    1. @Component({
    2. selector: 'app-ng-style-com',
    3. templateUrl: './ng-style-com.component.html',
    4. styleUrls: ['./ng-style-com.component.css']
    5. })
    6. export class NgStyleComComponent {
    7. status = true;
    8. //样式Obj
    9. switchStyles = {
    10. background: this.status ? 'green' : 'red',
    11. color: "white"
    12. }
    13. }
    1. <h1 [ngStyle]="switchStyles" >{{status ? "ON" : "OFF"}}</h1>
  • 查看输出结果:

image.png

  • 通过这种方式,如果想要修改元素样式,不需要对html文件进行修改,直接修改样式对象,一般样式定义在专门的样式文件中

    [ngClass]指令

  • 为了解决ngStyle样式绑定存在的CSS和TS脚本的耦合,使用ngClass解决

  • ngClass的主要作用时添加和删除多个CSS类,如果需要添加或删除单个类,应该使用类绑定而不是ngClass
  • ngClass的绑定值也必须是一个对象,这个对象的属性值时boolean值,true指定样式生效,false指定样式不生效

    1. ===========ng-class-com.component.css=========
    2. .status-success{
    3. color: green;
    4. }
    5. .status-error{
    6. color: red;
    7. }
    1. =============ng-class-com.component.html===========
    2. <h1 [ngClass]="status ? 'status-success' : 'status-error'" >
    3. {{status}}
    4. </h1>
    1. =============ng-class-com.component.ts===========
    2. @Component({
    3. selector: 'app-ng-class-com',
    4. templateUrl: './ng-class-com.component.html',
    5. styleUrls: ['./ng-class-com.component.css']
    6. })
    7. export class NgClassComComponent {
    8. status = false;
    9. }
  • 上述例子中将样式的判断逻辑放在了html文件中,开发过程中应该将逻辑处理放在ts脚本中

    1. ============ng-class-com.component.ts=============
    2. @Component({
    3. selector: 'app-ng-class-com',
    4. templateUrl: './ng-class-com.component.html',
    5. styleUrls: ['./ng-class-com.component.css']
    6. })
    7. export class NgClassComComponent {
    8. status = true;
    9. currentClass = {
    10. 'status-success': true,
    11. 'status-error': false
    12. };
    13. setCurrentStatus(){
    14. this.status = !this.status;
    15. this.currentClass = {
    16. 'status-success': !this.currentClass["status-success"],
    17. 'status-error': !this.currentClass["status-error"]
    18. }
    19. }
    20. }
    1. =============ng-class-com.component.html===========
    2. <h1 [ngClass]="currentClass" >
    3. {{status}}
    4. </h1>
    5. <button (click)="setCurrentStatus()">修改当前状态</button>
  • 查看效果

image.png

  • 点击修改后

image.png

*和[]修饰指令的区别

  • 在Angular中指令分为三种类型:

    • 结构型指令:会影响DOM树的结构,例如ngForngIF,所有的结构性指令必须使用*结构性指令方式使用
    • 属性型指令:不会影响DOM树的结构,只会影响元素外观的行为,例如ngClassngStyle,所有的属性型指令使用[属性指令]的方式使用
    • 组件:带有模板的指令

      5、双向数据绑定

      ngModel指令

  • ngModel:这个指令用于实现数据的双向绑定,双向指的是ModelView之间的绑定,Model改变View随之改变,View改变Model随之发生改变

  • ngModel绑定语法:[(ngModel)]="属性"
  • 要使用ngModel指令需要导入FormsModule模块

    1. ===========app.module.ts=============
    2. imports: [
    3. //Angular用于Web项目需要导入BrowserModule
    4. BrowserModule,
    5. //导入表单模块
    6. FormsModule
    7. ]
    1. ============ng-model-com.component.ts========
    2. @Component({
    3. selector: 'app-ng-model-com',
    4. templateUrl: './ng-model-com.component.html',
    5. styleUrls: ['./ng-model-com.component.css']
    6. })
    7. export class NgModelComComponent{
    8. userName = 'jack';
    9. }
    1. ==========ng-model-com.component.html============
    2. 用户名:<input [(ngModel)]="userName" placeholder="用户名"/>
    3. <h1>{{userName}}</h1>
  • 效果:根据双向绑定,显示内容将根据input标签中输入的内容进行绑定显示

image.png

  • 修改输入框中的内容,绑定显示内容因该随之发生改变

image.png

ngModelChange

  • ngModelChange用于监听模型数据的改变,语法:(ngModelChange)="fun()"

    1. 用户名:<input [(ngModel)]="userName"
    2. (ngModelChange)="nameChange()" placeholder="用户名"/>
    3. <h1>{{userName}}</h1>
    1. @Component({
    2. selector: 'app-ng-model-com',
    3. templateUrl: './ng-model-com.component.html',
    4. styleUrls: ['./ng-model-com.component.css']
    5. })
    6. export class NgModelComComponent{
    7. userName = 'jack';
    8. nameChange(){
    9. alert("Model Changed");
    10. }
    11. }
  • Model数据发生改变,触发绑定方法

image.png

案例:实现一个功能,输入框输入一个job,点击添加,添加到列表,每一个列表都有删除,将当前项从列表中移除

  1. @Component({
  2. selector: 'app-ng-model-com',
  3. templateUrl: './ng-model-com.component.html',
  4. styleUrls: ['./ng-model-com.component.css']
  5. })
  6. export class NgModelComComponent{
  7. addJob = '';
  8. addBtn = true;
  9. jobs: string[] = [];
  10. checkJobName(){
  11. this.addBtn = this.addJob.length <= 0 || this.jobs.indexOf(this.addJob) !== -1;
  12. }
  13. doAddJob(){
  14. this.jobs.push(this.addJob)
  15. this.addJob = '';
  16. this.addBtn = true;
  17. }
  18. doDeleteJob(index: number){
  19. this.jobs.splice(index, 1);
  20. }
  21. }
  1. 添加工作:<input [(ngModel)]="addJob" (ngModelChange)="checkJobName()"/>
  2. <button (click)="doAddJob()" [disabled]="addBtn">添加</button>
  3. <div *ngFor="let job of jobs; index as i">
  4. <span>{{job}}</span><button (click)="doDeleteJob(i)">删除</button>
  5. </div>
  • 实现效果:

image.png

6、自定义指令

  • 上述的指令都是Angular内置的指令,我们也可以自定义指令,本质上指令也是一种组件
  • 指令是作为标签元素的属性来使用的:
    • 因此他的选择器使用selector: "[指令名]"来定义
  • 创建一个指令的快捷方式:

    • 指令的存放位置位置app根目录下
    • 同时在app.module.ts@declaration中注册声明自定义的指令
      1. C:\Users\92541\Desktop\sd-wan\myngapp01>ng g directive tagging
      2. CREATE src/app/tagging.directive.spec.ts (228 bytes)
      3. CREATE src/app/tagging.directive.ts (143 bytes)
      4. UPDATE src/app/app.module.ts (1343 bytes)
  • 指令使用@Directive装饰器装饰,其只有选择器selector,指令是组件的父类,组件是一种特殊的指令

    1. ==========tagging.directive.ts===========
    2. @Directive({
    3. selector: '[appTagging]'
    4. })
    5. export class TaggingDirective {
    6. //通过构造函数
    7. constructor(e: ElementRef) {
    8. //nativeElement指的是使用指令的元素
    9. e.nativeElement.style.background = 'green';
    10. e.nativeElement.style.color = 'white'
    11. }
    12. }
    1. <h1 appTagging>使用自定义指令tagging</h1>
    2. <h1>不使用自定义指令tagging</h1>
  • 运行查看自定义指令的效果

image.png