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 效果图

 

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