Angular 4 指令快速入門教程,angular入門教程

來源:互聯網
上載者:User

Angular 4 指令快速入門教程,angular入門教程

本系列教程的開發環境及開發語言:

  1. Angular 4 +
  2. Angular CLI
  3. TypeScript

基礎知識

Angular CLI 基本使用

安裝 Angular CLI (可選)

npm install -g @angular/cli

建立新的項目

ng new PROJECT-NAME

啟動本機伺服器

cd PROJECT-NAMEng serve

Angular 指令簡介

Angular 的指令分為三種:

  1. 組件(Component directive):用於構建UI組件,繼承於 Directive 類
  2. 屬性指令(Attribute directive):用於改變組件的外觀或行為
  3. 結構指令(Structural directive):用於動態添加或刪除 DOM 元素來改變 DOM 布局

Angular 指令分類圖

Angular 組件組成圖

第一節 - 建立指令

在 Angular 中,我們可以使用 HostBinding 裝飾器,實現元素的屬性綁定。

指令的作用

該指令用於示範如何利用 HostBinding 裝飾器,設定元素的 innerText 屬性。

指令的實現

import { Directive, HostBinding} from '@angular/core';@Directive({  selector: '[greet]'})export class GreetDirective { @HostBinding() innerText = 'Hello, Everyone!';}指令的應用import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <h2>Hello, Angular</h2>  <h2 greet>Hello, Angular</h2> `,})export class AppComponent { }

第二節 - 定義輸入屬性

為了能夠讓使用者自訂 GreetDirective 指令的問候內容,我們需要使用 Input 裝飾器去定義指令的輸入屬性。

指令的作用

該指令用於示範如何利用 Input 裝飾器,定義指令的輸入屬性,從而實現讓使用者自訂問候內容。

指令的實現

import { Directive, HostBinding, Input } from '@angular/core';@Directive({  selector: '[greet]'})export class GreetDirective {  @Input() greet: string;  @HostBinding() get innerText() {    return this.greet;  }}

指令的應用

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <h2>Hello, Angular</h2>  <h2 [greet]="'Hello, Semlinker!'">Hello, Angular</h2> `,})export class AppComponent { }

第三節 - 事件處理

在 Angular 中,我們可以使用 HostListener 屬性裝飾器,實現元素的事件綁定。

指令的作用

該指令用於示範如何利用 HostListener 裝飾器,監聽使用者的點擊事件。

指令的實現

import { Directive, HostBinding, HostListener, Input } from '@angular/core';@Directive({  selector: '[greet]'})export class GreetDirective {  @Input() greet: string;  @HostBinding() get innerText() {   return this.greet;  }  @HostListener('click',['$event'])   onClick(event) {   this.greet = 'Clicked!';  }}

指令的應用

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <h2>Hello, Angular</h2>  <h2 [greet]="'Hello, Semlinker!'">Hello, Angular</h2> `,})export class AppComponent { }

第四節 - 擷取宿主要元素屬性值

在 Angular 中,我們可以通過 Attribute 裝飾器來擷取指令宿主要元素的屬性值。

指令的作用

該指令用於示範如何利用 Attribute 裝飾器,擷取指令宿主要元素上的自訂屬性 author 的值。

指令的實現

import { Directive, HostBinding, HostListener, Input, Attribute } from '@angular/core';@Directive({  selector: '[greet]'})export class GreetDirective {  @Input() greet: string;  @HostBinding() get innerText() {    return this.greet;  }  @HostListener('click',['$event'])   onClick(event) {    this.greet = 'Clicked!';    console.dir(event);  }  constructor(@Attribute('author') public author: string) {    console.log(author);  }}

指令的應用

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <h2>Hello, Angular</h2>  <h2 [greet]="'Hello, Semlinker!'"    author="semlinker">Hello, Angular</h2> `,})export class AppComponent { }

第五節 - 使用 <ng-template> 元素

在 Angular 中,我們可以通過 ViewChild 裝飾器來擷取視圖中定義的模板元素,然後利用 ViewContainerRef 對象的 createEmbeddedView() 方法,建立內嵌視圖。

import { Component, TemplateRef, ViewContainerRef, ViewChild,  AfterViewInit } from '@angular/core';@Component({ selector: 'app-root', template: `  <ng-template #tpl>   Hello, Semlinker!  </ng-template> `,})export class AppComponent implements AfterViewInit{ @ViewChild('tpl') tplRef: TemplateRef<any>; constructor(private vcRef: ViewContainerRef) {} ngAfterViewInit() {  this.vcRef.createEmbeddedView(this.tplRef); }}

第六節 - 使用 ngTemplateOutlet 指令

ngTemplateOutlet 的作用

該指令用於基於已有的 TemplateRef 對象,插入對應的內嵌視圖。在應用 NgTemplateOutlet 指令時,我們可以通過 [ngTemplateOutletContext] 屬性來設定 EmbeddedViewRef 的內容物件。綁定的上下文應該是一個對象,此外可通過 let文法來聲明綁定內容物件屬性名稱。

ngTemplateOutlet 的使用

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <ng-template #stpl>   Hello, Semlinker!  </ng-template>  <ng-template #atpl>   Hello, Angular!  </ng-template>  <div [ngTemplateOutlet]="atpl"></div>  <div [ngTemplateOutlet]="stpl"></div> `,})export class AppComponent { }

ngOutletContext 的使用

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <ng-template #stpl let-message="message">   <p>{{message}}</p>  </ng-template>  <ng-template #atpl let-msg="message">   <p>{{msg}}</p>  </ng-template>  <ng-template #otpl let-msg>   <p>{{msg}}</p>  </ng-template>  <div [ngTemplateOutlet]="atpl"   [ngOutletContext]="context">  </div>  <div [ngTemplateOutlet]="stpl"   [ngOutletContext]="context">  </div>  <div [ngTemplateOutlet]="otpl"   [ngOutletContext]="context">  </div> `,})export class AppComponent { context = { message: 'Hello ngOutletContext!',   $implicit: 'Hello, Semlinker!' };}

第七節 - 建立結構指令

指令的功能

該指令實現 ngIf 指令相反的效果,當指令的輸入條件為 Falsy 值時,顯示DOM元素。

指令的實現

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';@Directive({  selector: '[exeUnless]'})export class UnlessDirective {  @Input('exeUnless')  set condition(newCondition: boolean) {    if (!newCondition) {       this.viewContainer.createEmbeddedView(this.templateRef);    } else {      this.viewContainer.clear();    }  }  constructor(private templateRef: TemplateRef<any>,    private viewContainer: ViewContainerRef) {  }}

指令的應用

import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `  <h2 *exeUnless="condition">Hello, Semlinker!</h2>  `,})export class AppComponent { condition: boolean = false;}

我有話說

Angular 中指令與組件有什麼關係?

組件繼承於指令,並擴充了與 UI 視圖相關的屬性,如 template、styles、animations、encapsulation 等。

結構指令中的 TemplateRef 與 ViewContainerRef 有什麼作用?

TemplateRef:用於表示內嵌的 template 模板元素,通過 TemplateRef 執行個體,我們可以方便建立內嵌視圖(Embedded Views),且可以輕鬆地訪問到通過 ElementRef 封裝後的 nativeElement。需要注意的是組件視圖中的 template 模板元素,經過渲染後會被替換成 comment 元素。

ViewContainerRef:用於表示一個視圖容器,可添加一個或多個視圖。通ViewContainerRef 執行個體,我們可以基於 TemplateRef 執行個體建立內嵌視圖,並能指定內嵌視圖的插入位置,也可以方便對視圖容器中已有的視圖進行管理。簡而言之,ViewContainerRef 的主要作用是建立和管理內嵌視圖或組件視圖。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.