Angular @HostBinding()和@HostListener()用法,

來源:互聯網
上載者:User

Angular @HostBinding()和@HostListener()用法,

@HostBinding()和@HostListener()在自訂指令時非常有用。@HostBinding()可以為指令的宿主要元素添加類、樣式、屬性等,而@HostListener()可以監聽宿主要元素上的事件。

@HostBinding()和@HostListener()不僅僅用在自訂指令,只是在自訂指令中用的較多

本文基於Angular2+

下面我們通過實現一個在輸入時即時改變字型和邊框顏色的指令,學習@HostBinding()和@HostListener()的用法。

import { Directive, HostBinding, HostListener } from '@angular/core';@Directive({ selector: '[appRainbow]'①})export class RainbowDirective{ possibleColors = [  'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff',  'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey' ];② @HostBinding('style.color') color: string; @HostBinding('style.borderColor') borderColor: string;③ @HostListener('keydown') onKeydown(){④  const colorPick = Math.floor(Math.random() * this.possibleColors.length);  this.color = this.borderColor = this.possibleColors[colorPick]; }}

說一下上面代碼的主要部分:

①:為我們的指令取名為appRainbow
 ②:定義我們需要展示的所有可能的顏色
③:定義並用@HostBinding()裝飾color和borderColor,用於設定樣式
④:用@HostListener()監聽宿主要元素的keydown事件,為color和borderColor隨機分配顏色

OK,現在就來使用我們的指令:

<input appRainbow>

效果就像這樣:

NOTE:別忘了把指令引入你的模組

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.