属性型指令(Angular Directives)

directives

属性型指令,通过属性的方式使用,用于改变DOM元素的行为或外观

ng create directives

1
$ ng generate directive shark --skip-tests

shark.directive.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
<span appShark>Fin!</span>
<!-- Shark Fin! -->

实现input和textarea前面不能输入空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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);
}
}
}

// useage
<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 全局只读样式
.readonly-form {
color:rgba(0, 0, 0, 0.38) !important;
.mat-form-field-outline{
color: rgba(0,0,0,0.06) !important;
}
}

// useage
<mat-form-field appearance="outline" fxFlex jhiReadOnlyStyle [readonlyItem]="isView">
<mat-label>用户名</mat-label>
<input [type]="'text'" formControlName='userName' matInput [readonly]="isView">
</mat-form-field>

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/2023/12/Angular/Directives/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!