angular自定义指令
2018-12-03 本文已影响0人
nzjcnjzx
import {Directive, HostBinding, HostListener} from '@angular/core';
@Directive({
selector: '[appRainbow]'
})
export class RainbowDirective {
possibleColors = [
'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff',
'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey'
];
@HostBinding('style.color') color: string;
// @HostBinding('style.border-color') borderColor: string; 绑定属性
@HostBinding('style.border-bottom-color') borderBottomColor: string;
@HostListener('keydown') newColor() { // 绑定事件
const colorPick = Math.floor(Math.random() * this.possibleColors.length);
this.color = this.borderBottomColor = this.possibleColors[colorPick];
}
}
<input type="text" appRainbow>
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({
selector: '[appMyunless]'
})
export class MyunlessDirective {
@Input('appMyunless')
set condition(newCondition: boolean){
if(newCondition){
this.viewContainer.createEmbeddedView(this.templateRef)
} else {
this.viewContainer.clear()
}
}
constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
}
}
<div *appMyunless="true">myuless</div>
import { Directive, ElementRef, Input, HostListener } from '@angular/core';
@Directive({
selector: '[appInput]'
})
export class InputDirective {
private el: HTMLElement
private defaultColor= 'blue'
@Input('appInput') background: string
// set background(colorName: string){
// this.setStyle(colorName)
// }
constructor(el: ElementRef) {
this.el = el.nativeElement
this.setStyle(this.defaultColor)
}
@HostListener('click')
onclick(){
this.background = this.background == 'blue'? 'red': 'blue'
this.setStyle(this.background)
}
setStyle(color: string){
console.log(color)
this.el.style.background = color
}
}
<div [appInput]="'red'">input</div>