欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2018年03月05日 14:22:56   作者:無er不樂  
本篇文章主要介紹了Angular @HostBinding()和@HostListener()用法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

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

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

本文基于Angular2+

下面我們通過實(shí)現(xiàn)一個(gè)在輸入時(shí)實(shí)時(shí)改變字體和邊框顏色的指令,學(xué)習(xí)@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,用于設(shè)置樣式
④:用@HostListener()監(jiān)聽宿主元素的keydown事件,為color和borderColor隨機(jī)分配顏色

OK,現(xiàn)在就來使用我們的指令:

<input appRainbow>

效果就像這樣:

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論