@HostBinding and @HostListener: what do they do and what are they for?

前端 未结 7 951
[愿得一人]
[愿得一人] 2020-11-30 16:57

In my meanderings around the world wide interweb, and now especially the angular.io style docs, I find many references to @HostBinding and @HostListener

7条回答
  •  悲哀的现实
    2020-11-30 17:47

    Here is a basic hover example.

    Component's template property:

    Template

    
    
    
    

    Some text.

    And our directive

    import {Component,HostListener,Directive,HostBinding} from '@angular/core';
    
    @Directive({
        // this directive will work only if the DOM el has the c_highlight class
        selector: '.c_highlight'
     })
    export class HostDirective {
    
      // we could pass lots of thing to the HostBinding function. 
      // like class.valid or attr.required etc.
    
      @HostBinding('style.backgroundColor') c_colorrr = "red"; 
    
      @HostListener('mouseenter') c_onEnterrr() {
       this.c_colorrr= "blue" ;
      }
    
      @HostListener('mouseleave') c_onLeaveee() {
       this.c_colorrr = "yellow" ;
      } 
    }
    

提交回复
热议问题