转载自 http://www.ngui.cc/news/show-130.html
在 Angular 中,我们可以通过 Attribute 装饰器来获取指令宿主元素的属性值。
指令的作用
该指令用于演示如何利用 Attribute 装饰器,获取指令宿主元素上的自定义属性 author 的值。
指令的实现
import { Directive, HostBinding, HostListener, Input, Attribute } from '@angular/core';
<@Directive({
selector: '[greet]' }) export class GreetDirective {
@Input() greet: string;
@HostBinding() get innerText() { return this.greet;
}
@HostListener('click',['$event'])
onClick(event) { this.greet = 'Clicked!'; console.dir(event);
}
constructor(@Attribute('author') public author: string) { console.log(author);
}
}
指令的应用
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h2>Hello, Angular</h2>
<h2 [greet]="'Hello, Semlinker!'"
author="semlinker">Hello, Angular</h2>
`,
})
export class AppComponent { }