ایجاد Attribute برای کامپوننت های Angular2
نویسنده: علی یگانه مقدم
تاریخ: ۱۳۹۵/۱۲/۳۰ ۱۷:۱۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
<img [src]="...." />
<img [ngClass]='..' />
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective implements OnInit {
_dval = 'green';
constructor(private _ref: ElementRef) {
}
ngOnInit(): void {
this._ref.nativeElement.style.backgroundColor = this._dval;
}
} <span appHighlight>Attibute Directive</span>
حال ممکن است که بخواهید به این ویژگی مقداری را نسبت دهید و از طریق این مقدار، عملیات مورد نظر را انجام دهید. به عنوان نمونه در اینجا میخواهیم رنگ پس زمینه را در همان تگ معرفی کنیم:
پس کلاس دایرکتیو را به شکل زیر بازنویسی میکنیم:
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]',
inputs: ["hc"]
})
export class HighlightDirective implements OnInit {
hc: string;
_dval = 'green';
constructor(private _ref: ElementRef) {
}
ngOnInit(): void {
this._ref.nativeElement.style.backgroundColor = this.hc || this._dval;
}
} @Input() hc:string;
this._ref.nativeElement.style.backgroundColor=this.hc || this._dval;
<h1 appHighlight [hc]="'red'"> َApp Works! </h1>
<h1 appHighlight [hc]="'red'" [hc2]="....." [hc3]="....." ....> App Works! </h1>
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]',
inputs: ["hc"],
host: {
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)': 'onMouseLeave()',
}
})
export class HighlightDirective implements OnInit {
hc: string;
_dval = 'green';
constructor(private _ref: ElementRef) {}
ngOnInit(): void {
this._ref.nativeElement.style.backgroundColor = this.hc || this._dval;
}
onMouseEnter() {
this._ref.nativeElement.style.backgroundColor = 'blue';
}
onMouseLeave() {
this._ref.nativeElement.style.backgroundColor = 'pink';
}
}