4 Angular-自定義指令

1 代碼結構

 

 2 myc04.component.html

 1 <p>myc04 works!</p>
 2 
 3 <!--自定義指令-->
 4 <div>
 5     <input type="text">
 6 </div>
 7 <div>
 8     <!--自定義指令:ng generate directive 指令名-->
 9     <!--簡化寫法:ng g d 指令名-->
10     <!--appFocus指令可以讓輸入框自動獲取焦點-->
11     <input type="text" appFocus value="123">
12 </div>
13 <div>
14     <input type="text" value="hello" appUpper>
15 </div>
myc04.component.html

3 focus.directive.ts

 1 import { Directive, ElementRef } from '@angular/core';
 2 
 3 @Directive({
 4   selector: '[appFocus]'
 5 })
 6 export class FocusDirective {
 7 
 8   constructor(e: ElementRef) {
 9     //重啓命令行,生成新的指令必須重啓服務器才能生效
10     console.log(e)
11 
12     let input = e.nativeElement;//此處,指令綁定在input標籤上,所以是input標籤    
13     //DOM的原生方法,input的focus方法可以獲取焦點
14     input.focus();
15   }
16 
17 }
focus.directive.ts

4 upper.directive.ts

 1 import { Directive, ElementRef } from '@angular/core';
 2 
 3 @Directive({
 4   selector: '[appUpper]'
 5 })
 6 export class UpperDirective {
 7 
 8   constructor(e: ElementRef) {
 9     e.nativeElement.value = e.nativeElement.value.toUpperCase();
10   }
11 
12 }
upper.directive.ts

5 效果圖

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章