Кто-нибудь создал образец угловой директивы с использованием @Directive
декоратора? Я много искал, однако до сих пор все разработчики создали директивы компонентов. Даже в Angular API Review больше об этом не говорится.
Угловая директива
Ответы (5)
Демонстрация простой директивы. Это очень простой пример для начала с директивой angular2.
У меня есть компонент и директива.
Я использую директиву для обновления представления компонента. Кроме того, функция changeColor директивы вызывается с помощью функции changeColor компонента.
Компонент
@Component({
selector: 'my-app',
host: {'[style.backgroundColor]':'color',}
template: `
<input type="text" [(ngModel)]="color" (blur)="changeColor(color)" />
<br>
<span > (span) I'm {{color}} color <span>
<div mySelectedColor [selectedColor]="color"> (div) I'm {{color}} color </div>
`,
directives: [selectedColorDirective]
})
export class AppComponent implements AfterViewInit{
@ViewChild(selectedColorDirective) myDirective: selectedColorDirective;
color:string;
constructor(el:ElementRef,renderer:Renderer) {
this.color="Yellow";
//renderer.setElementStyle(el, 'backgroundColor', this.color);
}
changeColor(color)
{
this.myDirective.changeColor(this.color);
}
ngAfterViewInit() { }
}
Директива
@Directive({
selector:"[mySelectedColor]",
host: {
// '(keyup)': 'changeColor()',
// '[style.color]': 'selectedColor',
}
})
export class selectedColorDirective {
@Input() selectedColor: string = '';
constructor(el: ElementRef, renderer: Renderer) {
this.el=el;
this.el.nativeElement.style.backgroundColor = 'pink';
// renderer.setElementStyle(el, 'backgroundColor', this.selectedColor);
}
changeColor(clr)
{
console.log('changeColor called ' + clr);
//console.log(this.el.nativeElement);
this.el.nativeElement.style.backgroundColor = clr;
}
}
Проще говоря, директива компонента будет вашими директивами с шаблоном, который мы часто используем при создании приложения -> в вашем html -> <custom-tag></custom-tag>
@Component({
selector : 'custom-tag',
template : '<p> My Custom Tag</p>'
})
Структурные директивы - это те, которые изменяют DOM, удаляя добавленные элементы. Пример был бы
<div *ngIf="showErrorMessage">{{errorMessage}}</div>
ngIf добавит div, если true, иначе удалит, если он изменится на false.
И, наконец, директива атрибутов, название говорит само за себя ... ее «директива на основе атрибутов». Пример:
<input type="text" pPassword />
@Directive({
selector: '[pPassword]'
})
Есть три вида директив Angular:
Components
Attribute directives
Structural directives
Код директивы атрибутов руководства Angular2: https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/attribute-directives.
Код структурных директив руководства Angular2: https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives
Вот пример директивы. Это добавит прослушиватель событий для щелчка, выполненного вне компонента.
import {Directive, ElementRef, HostListener, EventEmitter, Output} from '@angular/core';
@Directive({
selector: '[clickedOutside]'
})
export class ClickedOutsideDirective {
@Output()
public clickedOutside = new EventEmitter();
constructor(private _elemRef: ElementRef) {
}
@HostListener('document:click', ['$event'])
public onClick(event) {
const targetElement = event.target;
if (!targetElement) {
return;
}
/**
* In case the target element which was present inside the referred element
* is removed from the DOM before this method is called, then clickedInside
* will be false even if the clicked element was inside the ref Element. So
* if you don't want this behaviour then use [hidden] instead of *ngIf
*/
const clickedInside = this._elemRef.nativeElement.contains(targetElement);
if (!clickedInside && !this._elemRef.nativeElement.isSameNode(targetElement)) {
return this.clickedOutside.emit(event);
}
}
}
Это можно использовать следующим образом:
<app-comp (clickedOutside)='close()'></app-comp>
close
будет срабатывать каждый раз, когда кто-то нажимает кнопку вне app-comp
Согласно документации Angular2, директивы используются для изменения поведения элемента DOM.
Давайте создадим одну директиву, которая изменит цвет фона div на красный в случае mouseenter и желтый в случае mouseleave.
Шаг 1. Создайте компонент
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '<div colorFlip>This is just a Demo!</div>'
})
export class MyComp {}
Шаг 2: Создайте директиву
import {Directive, HostListener, ElementRef} from '@angular/core';
@Directive({
selector: '[colorFlip]'
})
export class ColorFlip {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') handleMouseEnter() {
this.flipColor('red');
}
@HostListener('mouseleave') handleMouseEnter() {
this.flipColor('yellow');
}
flipColor(color:string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Шаг 3. Зарегистрируйте директиву
@NgModule({
imports: [...],
declarations: [MyComp , ColorFlip ]
})