คุณตรวจสอบเอกสารอย่างเป็นทางการเหล่านี้แล้วหรือยัง
HostListener - ประกาศฟังโฮสต์ เชิงมุมจะเรียกใช้วิธีการตกแต่งเมื่อองค์ประกอบโฮสต์ส่งเสียงเหตุการณ์ที่ระบุ
@HostListener- จะฟังเหตุการณ์ที่ปล่อยออกมาโดยองค์ประกอบโฮสต์ที่ประกาศ@HostListenerไว้
HostBinding - ประกาศการเชื่อมโยงคุณสมบัติโฮสต์ เชิงมุมตรวจสอบการผูกคุณสมบัติของโฮสต์โดยอัตโนมัติในระหว่างการตรวจจับการเปลี่ยนแปลง หากการเปลี่ยนแปลงมีผลผูกพันก็จะปรับปรุงองค์ประกอบโฮสต์ของคำสั่ง
@HostBinding- จะผูกคุณสมบัติกับองค์ประกอบโฮสต์หากการเปลี่ยนแปลงมีผลผูกพันHostBindingจะอัปเดตองค์ประกอบโฮสต์
หมายเหตุ:ลิงค์ทั้งสองถูกลบออกไปเมื่อเร็ว ๆ นี้ ส่วน " HostBinding-HostListening " ของคู่มือสไตล์อาจเป็นทางเลือกที่มีประโยชน์จนกว่าลิงก์จะกลับมา
ต่อไปนี้เป็นตัวอย่างโค้ดแบบง่ายเพื่อช่วยให้เข้าใจว่านี่หมายถึงอะไร:
DEMO: นี่คือตัวอย่างของการสาธิตแบบสดใน plunker - "ตัวอย่างง่ายๆเกี่ยวกับ @HostListener & @HostBinding"
- ตัวอย่างนี้ผูก
roleคุณสมบัติ - ประกาศด้วย@HostBinding- กับองค์ประกอบของโฮสต์
- จำได้ว่าเป็นคุณลักษณะเนื่องจากเรากำลังใช้
roleattr.role
<p myDir>กลายเป็น<p mydir="" role="admin">เมื่อคุณดูในเครื่องมือสำหรับนักพัฒนา
- จากนั้นจะฟัง
onClickเหตุการณ์ที่ประกาศไว้@HostListenerซึ่งแนบกับองค์ประกอบโฮสต์ขององค์ประกอบเปลี่ยนไปroleด้วยการคลิกแต่ละครั้ง
- การเปลี่ยนแปลงเมื่อ
<p myDir>คลิกถูกคือแท็กเปิดของเปลี่ยนจาก<p mydir="" role="admin">เป็น<p mydir="" role="guest">และย้อนกลับ
directives.ts
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 {}