Angular 指令
Angular Directive
有没有人使用 @Directive
decorator 创建了任何样本 Angular 指令?我搜索了很多,但是到目前为止所有开发人员都创建了组件指令。就连 Angular API Review也不多说这个了。
Simple-Directive-Demo。 这是一个非常简单的例子,从 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;
}
}
有3种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
简单来说
Component Directive 将是您在构建应用程序时经常使用的带有模板的指令 -> 在您的 html -> <custom-tag></custom-tag>
@Component({
selector : 'custom-tag',
template : '<p> My Custom Tag</p>'
})
结构指令 是通过删除添加元素来修改 DOM 的指令。
例如
<div *ngIf="showErrorMessage">{{errorMessage}}</div>
ngIf 将添加 div 如果它变为 false 则删除。
最后是属性指令,名字说明了一切..它是一个'attribute based directive'
例如:
<input type="text" pPassword />
@Directive({
selector: '[pPassword]'
})
这是一个示例指令。这为在组件外部完成的点击添加了一个事件侦听器。
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 ]
})
有没有人使用 @Directive
decorator 创建了任何样本 Angular 指令?我搜索了很多,但是到目前为止所有开发人员都创建了组件指令。就连 Angular API Review也不多说这个了。
Simple-Directive-Demo。 这是一个非常简单的例子,从 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;
}
}
有3种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
简单来说
Component Directive 将是您在构建应用程序时经常使用的带有模板的指令 -> 在您的 html -> <custom-tag></custom-tag>
@Component({
selector : 'custom-tag',
template : '<p> My Custom Tag</p>'
})
结构指令 是通过删除添加元素来修改 DOM 的指令。 例如
<div *ngIf="showErrorMessage">{{errorMessage}}</div>
ngIf 将添加 div 如果它变为 false 则删除。
最后是属性指令,名字说明了一切..它是一个'attribute based directive' 例如:
<input type="text" pPassword />
@Directive({
selector: '[pPassword]'
})
这是一个示例指令。这为在组件外部完成的点击添加了一个事件侦听器。
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 ]
})