import {ElementRef, Directive } from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
constructor(
private el: ElementRef
) {
this.el.nativeElement.style.color = 'red';
}
}
こちらを作成しておけば以下のようにDirectiveが利用できます。
<p myDirective>
myDirective works!
</p>
引数を利用したい場合は@Input() を利用します。
import {ElementRef, Directive, Input , OnInit} from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements OnInit {
@Input() myDirective;
constructor(
private el: ElementRef
) {}
ngOnInit() {
this.el.nativeElement.style.color = this.myDirective;
}
}
以下のようにDirectiveが利用できます。
<p myDirective="red">
myDirective works!
</p>
引数を複数設定したい場合はディレクティブ名以外の@Inputを増やしていきます。
import {ElementRef, Directive, Input , OnInit} from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements OnInit {
@Input() myDirective;
@Input() myDirectiveBg;
constructor(
private el: ElementRef
) {}
ngOnInit() {
this.el.nativeElement.style.color = this.myDirectiveBg;
this.el.nativeElement.style.backgroundColor = this.myDirectiveBg;
}
}
以下のようにDirectiveが利用できます。
<p myDirective="red" myDirectiveBg="blue">
myDirective works!
</p>
@HostListenerをを利用すればイベントを制御することも可能です。HostListenerの引数にイベントを設定して、実行したいメッソッドを後ろに指定します。
import {ElementRef, Directive, Input , OnInit, HostListener} from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements OnInit {
@Input() myDirective = 'blue';
@Input() myDirectiveBg = 'blue';
constructor(
private el: ElementRef
) {}
ngOnInit() {
this.el.nativeElement.style.color = this.myDirective;
}
@HostListener('click') changeBg() {
this.el.nativeElement.style.backgroundColor = this.myDirectiveBg;
}
}
@HostListenerは第2引数に配列でメソッドで利用できる引数が設定できます、'$event'と指定をするとイベントオブジェクトを利用することができます。(以下のサンプルではevent.targetをHTMLElement型にキャストしています。)
import {ElementRef, Directive, Input , OnInit, HostListener} from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective implements OnInit {
@Input() myDirective = 'blue';
@Input() myDirectiveBg = 'blue';
constructor(
private el: ElementRef
) {}
ngOnInit() {
this.el.nativeElement.style.color = this.myDirective;
}
@HostListener('click', ['$event']) changeBg(event: MouseEvent) {
(<HTMLElement>event.target).style.backgroundColor = this.myDirectiveBg;
}
}
タグ:Directive
【Angularの最新記事】
- Angularの構造ディレクティブ(St..
- AngularのRenderer2でDO..
- AngularでネイティブのDOMにアク..
- Angularでカスタムパイプを作る
- AngularでURLのパラメーターを取..
- AngularでN文字以上をトリミング
- AngularでBehaviorSubj..
- Angularで「WARNING .. ..
- angularでdebounce
- angular cliで作ったプロジェク..
- Angular2でformControl..
- Angular2のloadChildre..
- ElementRef - @angula..
- Angular 2のng2-dragul..
- Angular 2のDatePipe
- Angular2のRouting2
- Angular2のRouting
- Angular2のライフサイクルメソッド..
- Angular2のサービス
- Angular2のコンポーネント