sourcecode

@HostBinding 및 @HostListener: 그들은 무엇을 하고 무엇을 위한 것입니까?

copyscript 2023. 5. 4. 20:25
반응형

@HostBinding 및 @HostListener: 그들은 무엇을 하고 무엇을 위한 것입니까?

전 세계 인터넷, 특히 현재 angular.io 스타일 문서에서 많은 언급을 발견했습니다.@HostBinding그리고.@HostListener그것들은 꽤 근본적인 것처럼 보이지만, 안타깝게도 현재 그들을 위한 문서는 약간 개략적입니다.

그것들이 무엇인지, 어떻게 작동하는지, 그리고 그것들의 사용에 대한 예를 들어줄 수 있는 사람이 있습니까?

그들이 하는 일을 기억하는 데 도움이 되는 빠른 팁 -

HostBinding('value') myValue;▁the같▁▁is▁와 정확히 같습니다.[value]="myValue"

그리고.

HostListener('click') myClick(){ }▁the같▁▁is▁와 정확히 같습니다.(click)="myClick()"


HostBinding그리고.HostListener 있고 것들은 지시문으로 쓰여 요.(...)그리고.[..](구성요소의) 템플릿 내부에 기록됩니다.

당신은 이 공식 문서들을 확인했습니까?

HostListener - 호스트 수신기를 선언합니다.Angular는 호스트 요소가 지정된 이벤트를 내보낼 때 장식된 메서드를 호출합니다.

@HostListener 호스트 요소에서 발생하는 이벤트를 수신합니다.@HostListener.

HostBinding - 호스트 속성 바인딩을 선언합니다.Angular는 변경 사항 감지 중에 호스트 속성 바인딩을 자동으로 확인합니다.바인딩이 변경되면 디렉티브의 호스트 요소가 업데이트됩니다.

@HostBinding 속성을 호스트 요소에 바인딩합니다. 바인딩이 변경되면HostBinding호스트 요소를 업데이트합니다.


참고: 최근에 두 링크가 모두 제거되었습니다.유형 안내서의 "HostBinding-HostListening" 부분은 링크가 돌아올 때까지 유용한 대안이 될 수 있습니다.


다음은 이것이 의미하는 바를 이해하는 데 도움이 되는 간단한 코드 예입니다.

데모: "@HostListener & @HostBinding에 대한 간단한 예" 플런커로 된 데모 라이브입니다.

  • 에서는 " 예다음같다니습과"를 바인딩합니다.role- 속성 - 선된속으로 @HostBinding주인이 필요로 하는 것처럼
    • 을 하시오.role우리가 사용하고 있기 때문에 속성입니다.attr.role.
    • <p myDir> 되다<p mydir="" role="admin">개발자 도구에서 볼 수 있습니다.
  • 그리고 나서 그것은 다음을 듣습니다.onClick가 선사언건된으로 되었습니다.@HostListener구성 요소의 호스트 요소에 연결, 변경role클릭할 때마다
    • 변화는 다음과 같습니다.<p myDir>가 클하면태에변서경니다됩가그에서 됩니다.<p mydir="" role="admin"><p mydir="" role="guest">그리고 뒤로.

지시문

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

@Directive({selector: '[myDir]'})
export class HostDirective {
    @HostBinding('attr.role') role = 'admin';
    @HostListener('click') onClick() {
        this.role= this.role === 'admin' ? 'guest' : 'admin';
    }
}

AppComponent.ts

import { Component,ElementRef,ViewChild } from '@angular/core';
import {HostDirective} from './directives';

@Component({
    selector: 'my-app',
    template:
        `
        <p myDir>
            Host Element 
            <br><br>
        
            We have a (HostListener) listening to this host's 
            <b>click event</b> declared with @HostListener
        
            <br><br>
        
            And we have a (HostBinding) binding <b>the role property</b>
            to host element declared with @HostBinding 
            and checking host's property binding updates.
            
            If any property change is found I will update it.
        </p>
        
        <div>
            View this change in the DOM of the host element 
            by opening developer tools, clicking the host element in the UI. 
        
            The role attribute's changes will be visible in the DOM.
        </div> 
        `,
    directives: [HostDirective]
})
export class AppComponent {}

다음은 기본 호버 예제입니다.

구성 요소의 템플릿 속성:

템플릿

<!-- attention, we have the c_highlight class -->
<!-- c_highlight is the selector property value of the directive -->

<p class="c_highlight">
    Some text.
</p>

그리고 우리의 지시는

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

은 또다좋은점은입니다.@HostBinding당신이 그것을 결합할 수 있다는 것입니다.@Input바인딩이 입력에 직접 의존하는 경우(예:

@HostBinding('class.fixed-thing')
@Input()
fixed: boolean;

요약:.

  • @HostBinding이 장식자는 클래스 속성을 호스트 요소의 속성에 바인딩합니다.
  • @HostListener이 장식자는 클래스 메소드를 호스트 요소의 이벤트에 바인딩합니다.

예:

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

@Component({
  selector: 'app-root',
  template: `<p>This is nice text<p>`,
})
export class AppComponent  {

  @HostBinding('style.color') color; 

  @HostListener('click')
  onclick() {
    this.color =  'blue';
  }

}

위의 예에서는 다음과 같은 현상이 발생합니다.

  • 클릭 이벤트에 이벤트 수신기가 추가됩니다. 클릭 이벤트는 구성 요소 내에서 클릭 이벤트가 발생할 때 발생합니다.
  • color 우리집의 .AppComponent는 래스는속다니에 .style.color구성 요소의 속성입니다.그래서 항상.color되었으므로 속이업되로므트가 됩니다.style.color 요소의
  • 결과적으로 구성 요소를 클릭할 때마다 색상이 업데이트됩니다.

에서 @Directive:

구성요소에 사용할 수 있지만 이러한 장식기는 종종 속성 지시어에 사용됩니다.에▁an우에 할 때@Directive호스트가 지시어가 배치된 요소를 변경합니다.다음 구성 요소 템플릿을 예로 들어 보겠습니다.

<p p_Dir>some paragraph</p>

는 여서p_Dir는대지침다니입한기에 입니다.<p>원소의언제@HostBinding또는@HostListener는 지시 내에서 됩니다. 이제 호스트는 " 이호스참지클사내용다니됩에서래스시제트"를 합니다.<p>.

이 주제에 혼란을 가중시키는 한 가지는 장식가에 대한 생각이 명확하지 않다는 것입니다. 그리고 우리가 이런 것을 고려할 때...

@HostBinding('attr.something') 
get something() { 
    return this.somethingElse; 
 }

그것은 접속자이기 때문에 작동합니다.다음과 같은 함수를 사용할 수 없습니다.

@HostBinding('attr.something') 
something() { 
    return this.somethingElse; 
 }

그지않경우은, 시의이점을 사용하는 것의 이 있습니다.@HostBinding경계 값이 변경될 때 변경 탐지가 실행되도록 보장합니까?

// begginers
@Component({
  selector: 'custom-comp',
  template: ` <div class="my-class" (click)="onClick()">CLICK ME</div> `,
})
export class CustomComp {
  onClick = () => console.log('click event');
}

// pros
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
})
export class CustomComp {
  @HostBinding('class.my-class') className = true;
  @HostListener('click') onClick = () => this.className = false;
}

// experts
@Component({
  selector: 'custom-comp',
  template: ` CLICK ME `,
  host: {
    class: 'my-class',
    '(click)': 'onClick()',
  },
})
export class CustomComp {
  onClick = () => console.log('click event');
}

첫 번째 방법은 다음과 같습니다.

<custom-comp>
   <div class="my-class" (click)="onClick()">
      CLICK ME
   <div>
</custom-comp>

두 번째와 세 번째 방법은 다음과 같습니다.

<custom-comp class="my-class" (click)="onClick()">
   CLICK ME
</custom-comp>

참고: 2일에 부활절 달걀을 찾았습니까?

자곤이 적은 이론

@Hostlistening은 기본적으로 호스트 요소(버튼)가 사용자의 작업을 듣고 특정 기능인 경고("Ahoy!")를 수행하는 반면 @Hostbinding은 반대입니다.여기서는 해당 버튼에서 내부적으로 발생한 변경 사항을 듣고(클릭된 시점을 예로 들어 클래스에 발생한 변경 사항) 해당 변경 사항을 사용하여 다른 작업을 수행합니다(예: 특정 색상을 내보냅니다).

구성 요소에 즐겨찾기 아이콘을 만들고 싶은 시나리오를 생각해 보십시오. 이제 클래스가 변경되어 항목이 즐겨찾기에 추가되었는지 여부를 알아야 합니다. 이를 확인할 수 있는 방법이 필요합니다.바로 여기서 @Hostbinding이 필요합니다.

사용자가 실제로 수행한 작업이 무엇인지 알아야 하는 경우 @Hostlistening이 제공됩니다.

메서드 장식자:

@호스트 바인딩:호스트 요소에 사용자 지정 논리를 동적으로 바인딩

 @HostBinding('class.active')
 activeClass = false;

@호스트 수신:호스트 요소에서 이벤트 수신 대기

@HostListener('click')
 activeFunction(){
    this.activeClass = !this.activeClass;
 }

호스트 요소:

  <button type='button' class="btn btn-primary btn-sm" appHost>Host</button>

언급URL : https://stackoverflow.com/questions/37965647/hostbinding-and-hostlistener-what-do-they-do-and-what-are-they-for

반응형