directives
属性型指令,通过属性的方式使用,用于改变DOM元素的行为或外观
ng
create directives
| $ ng generate directive shark --skip-tests
|
shark.directive.ts
| import {Directive, ElementRef, Renderer2} from '@angular/core';
@Directive( { selector: '[appShark]' } ) export class SharkDirective { creature = 'Dolphin';
constructor(elem: ElementRef, renderer: Renderer2) { let shark = renderer.createText('Shark '); renderer.appendChild(elem.nativeElement, shark); } }
|
app.component.html
| <span appShark>Fin!</span>
|
实现input和textarea前面不能输入空格
| @Directive({ selector: 'input[jhiNoHeadSpace],textarea[jhiNoHeadSpace]', }) export class NoHeadSpaceDirective { @HostListener('input', ['$event']) onInput($event: any) { if (/^\s+/g.test($event.target.value)) { $event.target.value = $event.target.value.replace(/^\s+/g, ""); $event.target.setSelectionRange(0, 0); } } }
<input formControlName="name" jhiNoHeadSpace matInput>
|
实现样式改变
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| @Directive({ selector: '[jhiReadOnlyStyle]', }) export class ReadonlyTypeDirective {
@Input() readonlyItem: boolean = false;
constructor(private el: ElementRef, private renderer: Renderer2) { }
ngAfterViewInit() { if (this.readonlyItem) { this.renderer.addClass(this.el.nativeElement, 'readonly-form') } } }
.readonly-form { color:rgba(0, 0, 0, 0.38) !important; .mat-form-field-outline{ color: rgba(0,0,0,0.06) !important; } }
<mat-form-field appearance="outline" fxFlex jhiReadOnlyStyle [readonlyItem]="isView"> <mat-label>用户名</mat-label> <input [type]="'text'" formControlName='userName' matInput [readonly]="isView"> </mat-form-field>
|