Angular 4 指令快速入門

目錄

  • 第一節(jié) - 創(chuàng)建指令
  • 第二節(jié) - 定義輸入屬性
  • 第三節(jié) - 事件處理
  • 第四節(jié) - 獲取宿主元素屬性值
  • 第五節(jié) - 使用 <ng-template> 元素
  • 第六節(jié) - 使用 ngTemplateOutlet 指令
  • 第七節(jié) - 創(chuàng)建結(jié)構(gòu)指令

閱讀須知

本系列教程的開發(fā)環(huán)境及開發(fā)語言:

基礎(chǔ)知識

Angular CLI 基本使用

npm install -g @angular/cli
  • 創(chuàng)建新的項(xiàng)目
ng new PROJECT-NAME
  • 啟動(dòng)本地服務(wù)器
cd PROJECT-NAME
ng serve

Angular 指令簡介

Angular 的指令分為三種:

  • 組件(Component directive):用于構(gòu)建UI組件勺鸦,繼承于 Directive 類
  • 屬性指令(Attribute directive):用于改變組件的外觀或行為
  • 結(jié)構(gòu)指令(Structural directive):用于動(dòng)態(tài)添加或刪除 DOM 元素來改變 DOM 布局

Angular 指令分類圖

angular-directive

Angular 組件組成圖

angular-component-compose

第一節(jié) - 創(chuàng)建指令

在 Angular 中,我們可以使用 HostBinding 裝飾器,實(shí)現(xiàn)元素的屬性綁定身笤。

指令的作用

該指令用于演示如何利用 HostBinding 裝飾器,設(shè)置元素的 innerText 屬性招狸。

指令的實(shí)現(xiàn)

import { Directive, HostBinding} from '@angular/core';

@Directive({
    selector: '[greet]'
})
export class GreetDirective {
  @HostBinding() innerText = 'Hello, Everyone!';
}

指令的應(yīng)用

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h2>Hello, Angular</h2>
    <h2 greet>Hello, Angular</h2>
  `,
})
export class AppComponent { }

第二節(jié) - 定義輸入屬性

為了能夠讓用戶自定義 GreetDirective 指令的問候內(nèi)容帽衙,我們需要使用 Input 裝飾器去定義指令的輸入屬性。

指令的作用

該指令用于演示如何利用 Input 裝飾器燕侠,定義指令的輸入屬性,從而實(shí)現(xiàn)讓用戶自定義問候內(nèi)容立莉。

指令的實(shí)現(xiàn)

import { Directive, HostBinding, Input } from '@angular/core';

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

指令的應(yīng)用

import { Component } from '@angular/core';

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

第三節(jié) - 事件處理

在 Angular 中绢彤,我們可以使用 HostListener 屬性裝飾器,實(shí)現(xiàn)元素的事件綁定蜓耻。

指令的作用

該指令用于演示如何利用 HostListener 裝飾器茫舶,監(jiān)聽用戶的點(diǎn)擊事件。

指令的實(shí)現(xiàn)

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!';
   }
}

指令的應(yīng)用

import { Component } from '@angular/core';

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

第四節(jié) - 獲取宿主元素屬性值

在 Angular 中刹淌,我們可以通過 Attribute 裝飾器來獲取指令宿主元素的屬性值饶氏。

指令的作用

該指令用于演示如何利用 Attribute 裝飾器讥耗,獲取指令宿主元素上的自定義屬性 author 的值。

指令的實(shí)現(xiàn)

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);
    }
}

指令的應(yīng)用

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 { }

第五節(jié) - 使用 <ng-template> 元素

在 Angular 中疹启,我們可以通過 ViewChild 裝飾器來獲取視圖中定義的模板元素古程,然后利用 ViewContainerRef 對象的 createEmbeddedView() 方法,創(chuàng)建內(nèi)嵌視圖喊崖。

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);
  }
}

第六節(jié) - 使用 ngTemplateOutlet 指令

ngTemplateOutlet 的作用

該指令用于基于已有的 TemplateRef 對象挣磨,插入對應(yīng)的內(nèi)嵌視圖。在應(yīng)用 NgTemplateOutlet 指令時(shí)荤懂,我們可以通過 [ngTemplateOutletContext] 屬性來設(shè)置 EmbeddedViewRef 的上下文對象茁裙。綁定的上下文應(yīng)該是一個(gè)對象,此外可通過 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!' };
}

第七節(jié) - 創(chuàng)建結(jié)構(gòu)指令

指令的功能

該指令實(shí)現(xiàn) ngIf 指令相反的效果呜达,當(dāng)指令的輸入條件為 Falsy 值時(shí),顯示DOM元素粟耻。

指令的實(shí)現(xiàn)

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) {
    }
}

指令的應(yīng)用

import { Component } from '@angular/core';

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

我有話說

Angular 中指令與組件有什么關(guān)系查近?

組件繼承于指令,并擴(kuò)展了與 UI 視圖相關(guān)的屬性挤忙,如 template霜威、styles、animations册烈、encapsulation 等戈泼。

詳細(xì)內(nèi)容請參考 - Angular 2 Directive Lifecycle

結(jié)構(gòu)指令中的 TemplateRefViewContainerRef 有什么作用?

TemplateRef:用于表示內(nèi)嵌的 template 模板元素赏僧,通過 TemplateRef 實(shí)例大猛,我們可以方便創(chuàng)建內(nèi)嵌視圖(Embedded Views),且可以輕松地訪問到通過 ElementRef 封裝后的 nativeElement淀零。需要注意的是組件視圖中的 template 模板元素挽绩,經(jīng)過渲染后會被替換成 comment 元素。

ViewContainerRef:用于表示一個(gè)視圖容器驾中,可添加一個(gè)或多個(gè)視圖唉堪。通ViewContainerRef 實(shí)例,我們可以基于 TemplateRef 實(shí)例創(chuàng)建內(nèi)嵌視圖肩民,并能指定內(nèi)嵌視圖的插入位置唠亚,也可以方便對視圖容器中已有的視圖進(jìn)行管理。簡而言之持痰,ViewContainerRef 的主要作用是創(chuàng)建和管理內(nèi)嵌視圖或組件視圖灶搜。

詳細(xì)內(nèi)容請參考 - Angular 2 TemplateRef & ViewContainerRef

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子割卖,更是在濱河造成了極大的恐慌前酿,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件究珊,死亡現(xiàn)場離奇詭異,居然都是意外死亡纵苛,警方通過查閱死者的電腦和手機(jī)剿涮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來攻人,“玉大人取试,你說我怎么就攤上這事』澄牵” “怎么了瞬浓?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蓬坡。 經(jīng)常有香客問我猿棉,道長,這世上最難降的妖魔是什么屑咳? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任萨赁,我火速辦了婚禮,結(jié)果婚禮上兆龙,老公的妹妹穿的比我還像新娘杖爽。我一直安慰自己,他們只是感情好紫皇,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布慰安。 她就那樣靜靜地躺著,像睡著了一般聪铺。 火紅的嫁衣襯著肌膚如雪化焕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天铃剔,我揣著相機(jī)與錄音锣杂,去河邊找鬼。 笑死番宁,一個(gè)胖子當(dāng)著我的面吹牛元莫,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蝶押,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼踱蠢,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起茎截,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤苇侵,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后企锌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體榆浓,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年撕攒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了陡鹃。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,727評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡抖坪,死狀恐怖萍鲸,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情擦俐,我是刑警寧澤脊阴,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站蚯瞧,受9級特大地震影響嘿期,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜埋合,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一秽五、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧饥悴,春花似錦坦喘、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至贷揽,卻和暖如春棠笑,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背禽绪。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工蓖救, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人印屁。 一個(gè)月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓循捺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親雄人。 傳聞我的和親對象是個(gè)殘疾皇子从橘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容