Angular 2 屬性指令

2018-01-04 15:42 更新

描述

attribute指令改變DOM元素的外觀或行為。 這些指令在模板中看起來像常規(guī)HTML屬性。 用于雙向的ngModel指令是屬性指令的示例。 下面列出了一些其他屬性偽指令:

  • NgSwitch:只要你想顯示一個由許多孩子組成的元素樹。 Angular僅基于某些條件將選定的元素樹放入DOM中。

  • NgStyle:基于組件狀態(tài),可以使用NgStyle設(shè)置動態(tài)樣式。 許多內(nèi)聯(lián)樣式可以通過綁定到NgStyle同時設(shè)置。

  • NgClass:它通過動態(tài)添加和刪除CSS類來控制元素的外觀。

例子

下面的例子描述了在Angular 2中使用屬性指令:

<html>
  <head>
    <title>Contact Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="/attachments/w3c/es6-shim.min.js"></script>
    <script src="/attachments/w3c/system-polyfills.js"></script>
    <script src="/attachments/w3c/angular2-polyfills.js"></script>
    <script src="/attachments/w3c/system.js"></script>
    <script src="/attachments/w3c/typescript.js"></script>
    <script src="/attachments/w3c/Rx.js"></script>
    <script src="/attachments/w3c/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
      });
      System.import('/angular2/src/app/attribute_main')
            .then(null, console.error.bind(console));
    </script>

  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

上述代碼包括以下配置選項:

  • 您可以使用typescript版本配置index.html文件。在使用transpiler選項運行應(yīng)用程序之前,SystemJS將TypeScript轉(zhuǎn)換為JavaScript。

  • 如果在運行應(yīng)用程序之前沒有翻譯到JavaScript,您可能會看到瀏覽器中隱藏的編譯器警告和錯誤。

  • 當(dāng)設(shè)置emitDecoratorMetadata選項時,TypeScript會為代碼的每個類生成元數(shù)據(jù)。如果不指定此選項,將生成大量未使用的元數(shù)據(jù),這會影響文件大小和對應(yīng)用程序運行時的影響。

  • Angular 2包括來自app文件夾的包,其中文件將具有.ts擴展名。

  • 接下來它將從應(yīng)用程序文件夾加載主組件文件。如果沒有找到主要組件文件,那么它將在控制臺中顯示錯誤。

  • 當(dāng)Angular調(diào)用main.ts中的引導(dǎo)函數(shù)時,它讀取Component元數(shù)據(jù),找到“app”選擇器,找到一個名為app的元素標(biāo)簽,并在這些標(biāo)簽之間加載應(yīng)用程序。

要運行代碼,您需要以下TypeScript(.ts)文件,您需要保存在應(yīng)用程序文件夾下。

attribute_main.ts
import {bootstrap} from 'angular2/platform/browser';       //importing bootstrap function
import {AppComponent} from "./attribute_app.component";    //importing component function

bootstrap(AppComponent);

現(xiàn)在我們將在TypeScript(.ts)文件中創(chuàng)建一個組件,我們將為該組件創(chuàng)建一個視圖。

attribute_app.component.ts
import {Component} from 'angular2/core';
import {ShoppingListComponent} from './shopping-item.component';

@Component({
    selector: 'my-app',
    template: `
    <shopping></shopping>
    `,
    directives: [ShoppingListComponent]
})
export class AppComponent {

}
  • @Component是一個裝飾器,它使用配置對象來創(chuàng)建組件及其視圖。

  • 選擇器創(chuàng)建組件的實例,在父HTML中找到<my-app>標(biāo)記。

  • 接下來,我們創(chuàng)建一個名為ShoppingListComponent的指令,它將從shopping-item.component文件中訪問。

shopping-item.component.ts
import {Component} from "angular2/core";
import {NgSwitch} from "angular2/core";
import {NgSwitchWhen} from "angular2/core";
import {NgSwitchDefault} from "angular2/core";
import {NgClass} from 'angular2/common';

@Component({
   selector: "shopping",
   template: `
       <h2>Shopping Items</h2>
       <ul>
          <li
          *ngFor="#shopItem of shopItems"
          (click)="onItemClicked(shopItem)"
          >{{ shopItem.name }}</li>
       </ul>

       <span [ngSwitch]=selectedItem.name>
         <p>You selected :
            <span *ngSwitchWhen="'Shirt'">Shirt</span>
            <span *ngSwitchWhen="'Pant'">Pant</span>
            <span *ngSwitchWhen="'Sarees'">Sarees</span>
            <span *ngSwitchWhen="'Jeans'">Jeans</span>
            <span *ngSwitchWhen="'T-Shirt'">T-Shirt</span>
            <span *ngSwitchDefault>Nothing</span>
         </p>
       </span>

       <div [ngStyle]="setStyles(selectedItem.name)" class="text-success">
          Thank you for Selecting an item!!
       </div>

       <button [ngClass]="{active: isActive}" (click)="isActive = !isActive">Buy Items</button>
   `,
   styles: [`
       .button {
          width: 120px;
          border: medium solid black;
       }
       .active {
          background-color: red;
       }
       p{
          font-weight: bold;
       }
   `]
   directives: [NgClass]
})

export class ShoppingListComponent {
   public shopItems = [
      {name: "Shirt"},
      {name: "Pant"},
      {name: "Sarees"},
      {name: "Jeans"},
      {name: "T-Shirt"},
   ];
   public selectedItem = {name: ""};
   onItemClicked(shopItem) {
      this.selectedItem = shopItem;
   }
   setStyles(item) {
      let styles = {
        'font-size'  : item? '24px'   : 'none',
        'visibility' : !item? 'hidden' : 'visible'
      }
      return styles;
   }
}
  • 局部變量shopItem可以在模板中引用并獲取數(shù)組的索引。 Angular 2將使用模板的局部變量綁定來自數(shù)組的模型名稱。

  • 當(dāng)你點擊項目的值,onItemClicked()事件將獲得激活和Angular 2將綁定模型名稱從數(shù)組與模板的局部變量。

  • NgSwitch指令根據(jù)匹配表達(dá)式與從評估的開關(guān)表達(dá)式獲得的值匹配插入嵌套元素。 它顯示一個元素,其* ngSwitchWhen匹配當(dāng)前的ngSwitch表達(dá)式值。

  • onItemClicked()方法使用局部變量“shopItem”作為參數(shù),并使用selectedItem對象顯示所選項目。

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:

  • 將上面的HTML代碼保存為index.html文件,如同我們在環(huán)境章節(jié)中創(chuàng)建的,并使用上面的包含.ts文件的應(yīng)用程序文件夾。

  • 打開終端窗口并輸入以下命令:

    npm start
  • 稍后,瀏覽器選項卡應(yīng)打開并顯示輸出,如下所示。

或者你可以用另一種方式運行這個文件:

  • 將上面的HTML代碼作為attribute_directive.html文件保存在服務(wù)器根文件夾中。

  • 將此HTML文件打開為http://localhost/attribute_directive.html,并顯示如下所示的輸出。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號