[Angular Directive] 1. Write an Angular Directive

本文介绍如何使用 Angular 2 创建自定义指令,并通过属性选择器将指令的行为附加到元素上。演示了一个简单的 TextDirective 示例,该指令能够改变带有 '[myText]' 属性的选择器元素的内部文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Angular 2 Directives allow you manipulate elements by adding custom behaviors through attributes. This lesson covers how to create a Directive and attach its behavior to an element.

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

@Directive({
  selector: '[myText]'
})
export class TextDirective {

  @HostBinding() innerText;
  constructor() {
    this.innerText = "I am text directive!"
  }
}

 

There are tow things important here:

  • selector: '[myText]', this is an attr selector.
  • HostBinding: Bind to host element's props.

If we using like this:

<div myText>I am a div</div>
<span>I am a span</span>
<hr>
<span myText>My text will be changed!</span>

This directive will change div and last span's innerText to 'I am text directive!'.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值