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

175 篇文章 1 订阅
139 篇文章 0 订阅

原文出处:https://blog.csdn.net/qq_36451496/article/details/86690382

@HostBinding()和@HostListener()在自定义指令时非常有用。
@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随机分配颜色

在页面上使用这个指令:

<input appRainbow>

 效果如下:

Angular中的@Input和@Output是用来实现组件之间通信的注解。 @Input用来接收父组件传递过来的数据,而@Output则用来向父组件传递数据。 下面是它们的使用方法: 1. @Input 在子组件中使用@Input注解来接收父组件传递的数据。例如: ``` import { Component, Input } from '@angular/core'; @Component({ selector: 'child-component', template: ` <div>{{data}}</div> ` }) export class ChildComponent { @Input() data: string; } ``` 在父组件中使用属性绑定的方式将数据传递给子组件。例如: ``` import { Component } from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child-component [data]="myData"></child-component> ` }) export class ParentComponent { myData = 'Hello world'; } ``` 2. @Output 在子组件中使用@Output注解来定义一个事件。例如: ``` import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'child-component', template: ` <button (click)="onClick()">Click me</button> ` }) export class ChildComponent { @Output() clicked = new EventEmitter<void>(); onClick() { this.clicked.emit(); } } ``` 在父组件中使用事件绑定的方式监听子组件的事件。例如: ``` import { Component } from '@angular/core'; @Component({ selector: 'parent-component', template: ` <child-component (clicked)="onChildClicked()"></child-component> ` }) export class ParentComponent { onChildClicked() { console.log('Child component clicked'); } } ``` 这样就实现了子组件向父组件传递数据的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值