浅谈Angularjs至Angular2后内置指令的变化

image.png

一、科普概要说明
  • 我们常说的 Angular 1 是指 AngularJS; 从Angular 2 开始已经改名了。不再带有JS,只是单纯的 Angular
  • Angular 1.x 是基于JavaScript的框架,Angular2后是基于 TypeScript来写的
    有兴趣的朋友可以了解下NG-ZORRO Ant Design of Angular https://ng.ant.design/docs/introduce/zh
  • Angular 官方文档 地址https://angular.io/
  • 开发脚手架 https://cli.angular.io/
  • TypeScript 入门文档 https://www.typescriptlang.org/
    初步了解下TypeScript的语法
    image.png
二、详解部分内置指令的变化

(1)、Angular(ng-if) -- Angular2(*ngIf)

语法 <element ng-if="expression"></element>
ng-if 指令用于在表达式为 false 时移除 HTML 元素。
如果 if 语句执行的结果为 true,会添加移除元素,并显示

<div *ngIf="false"></div>
<div *ngIf="myFunction()"></div>

(2)、Angular(ng-repeat) -- Angular2(*ngFor)

ng-repeat 指令用于循环输出指定次数的 HTML 元素。集合必须是数组或对象
Angular 2.x 中不存在 ng-repeat 指令,取而代之的是 ngFor 指令。它们的语法非常相似,
但需要注意的一点在遍历集合是,Angular 2 使用 of 代替了 in 。
<tr ng-repeat="x in records">
        <td>{{x.Name}}</td>
        <td>{{x.Country}}</td> 
</tr>
<ul>
        <li *ngFor="let grocery of groceries; let i = index;">
          <a href="#" (click)="selectGrocery(grocery);">
            {{ grocery.label }} {{ i }}
          </a>
        </li>
</ul>

(3)、Angular(ng-switch) -- Angular2(ngSwitch)

ng-switch 指令根据表达式显示或隐藏对应的部分。
对应的子元素使用 ng-switch-when 指令,如果匹配选中选择显示,其他为匹配的则移除。
你可以通过使用 ng-switch-default 指令设置默认选项,如果都没有匹配的情况,默认选项会显示。
作用 防止条件复杂的情况导致过多的使用 ngIf。
<element ng-switch="expression">
  <element ng-switch-when="value"></element>
  <element ng-switch-when="value"></element>
  <element ng-switch-when="value"></element>
  <element ng-switch-default></element>
</element>

<div class="container" [ngSwitch]="myAge">
 <div *ngSwitchCase="'10'">age = 10</div>
 <div *ngSwitchCase="'20'">age = 20</div>
 <div *ngSwitchDefault="'18'">age = 18</div>
</div>

(4)、Angular(ng-style) -- Angular2(ngStyle)

ng-style 指令为 HTML 元素添加 style 属性。
ng-style 属性值必须是对象,表达式返回的也是对象。对象由 CSS 属性和值组成,即 key=>value 对。
使用动态值给特定的 DOM 元素设定 CSS 属性。
<h1 ng-style="{
        "color" : "white",
        "background-color" : "coral",
        "font-size" : "60px",
        "padding" : "50px"
    }">菜鸟教程</h1>

<div [style.color]="yellow">
</div>
<div [style.background-color]="backColor">
</div>
<div [style.font-size.px]="20">
</div>
<div [ngStyle]="{color: 'white', 'background-color': 'blue', 'font-size.px': '20'}">
</div>

(5)、Angular(ng-class) -- Angular2(ngClass)

ng-class 指令用于给 HTML 元素动态绑定一个或多个 CSS 类。
ng-class 指令的值可以是字符串,对象,或一个数组。
如果是字符串,多个类名使用空格分隔。
如果是对象,需要使用 key-value 对,key 为你想要添加的类名,value 是一个布尔值。只有在 value 为 true 时类才会被添加。
如果是数组,可以由字符串或对象组合组成,数组的元素可以是字符串或对象。
<div ng-class="home">
    <h1>Welcome Home!</h1>
    <p>I like it!</p>
</div>
<div [ngClass]="{active: isActive}">               // 例子1
<div [ngClass]="{active: isActive,
                 shazam: isImportant}">            // 例子2
<div [class.active]="isActive">               // 例子3

在第一个例子中,如果isActive为真,则active类被应用到那个元素上。
还可以同时指定多个类,例如第二个例子。
Angular还有类绑定,它是单独添加或移除一个类的好办法,就像第三个例子中展示的。

(6)、Angular(ng-click) -- Angular2((click))

HTML 元素被点击后需要执行的操作
<element ng-click="expression"></element>
<button (click)="toggleImage()">        // 例子1
<button (click)="toggleImage($event)">    // 例子2
在第一个例子中,当用户点击此按钮时,相关组件中的toggleImage()方法就被执行了。
第二个例子演示了如何传入$event对象,它为组件提供了此事件的详情。

(7)、Angular(ng-model) -- Angular2(ngModel)

<element ng-model="name"></element> 绑定了 HTML 表单元素到 变量中
单向绑定 - [ngModel]
<form novalidate #f="ngForm">
      Name: <input type="text" name="username" [ngModel]="user.username">
   </form>
双向绑定 - [(ngModel)]
<form novalidate #f="ngForm">
      Name: <input type="text" name="username"  [(ngModel)]="user.username">
   </form>

(8)、Angular(ng-value) -- Angular2(ngModel)

ng-value 指令用于设置 input 或 select 元素的 value 属性。
<input ng-value="myVar">
 <select id='personHobbies' class='form-control'
          name='personHobbies' [(ngModel)]='activePerson.hobbyList[i]'>
          <option *ngFor='let h of hobbyListSelect;' [ngValue]='h'>{{h.name}}</option>
        </select>

最后科普下Angular 父子组件之间参数传递的问题 (@input @output :在子组件引入父组件的元素时,@Input往往是值,@Output是指事件)

父组件到子组件:父组件用属性绑定将值传入,子组件通过@Input来接收。
// 父组件
import { Component } from '@angular/core'; 
@Component({
  selector: 'hero-parent',
  template: `<h2> heroes </h2>
    <hero-child *ngFor="let hero of heroes"
      [hero]="hero" >
    </hero-child>
  `
})
export class HeroParentComponent {
  heroes = [{
    name: 'John'
  }, {
    name: 'Lily'
  }]; 
}
// 子组件
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
  selector: 'hero-child',
  template: `
    <h3>{{hero.name}}</h3> 
  `
})
export class HeroChildComponent {
  @Input() hero: Hero; 
}

子组件到父组件:子组件自定义事件用@Output传出,父组件用事件绑定获取。
// 子组件
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
  selector: 'my-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)">Agree</button> 
  `
})
export class VoterComponent { 
  @Output() onVoted = new EventEmitter<boolean>(); 
  vote(agreed: boolean) {
    this.onVoted.emit(agreed); 
  }
}
// 父组件
import { Component } from '@angular/core';
@Component({
  selector: 'vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
    <my-voter *ngFor="let voter of voters"
      [name]="voter"
      (onVoted)="onVoted($event)">
    </my-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}
父组件的类需要读取子组件的属性值或调用子组件的方法:子组件作为ViewChild,注入到父组件里面

image.png

image.png

猜你喜欢

转载自www.cnblogs.com/24klr/p/11320478.html
今日推荐