Angular之自定义指令

1.自定义指令
这里我们说的指令可以理解为 属性型指令,主要是用来控制组件的外观的。

2.自定义指令的生成

ng gengerate directive directives/my-style

3.目录
在前面的基础上:


image.png

4.自定义指令的使用

指令ts文件代码:

import { Directive,ElementRef,HostListener,Input } from    
'@angular/core'; 
@Directive({
 selector: '[appMyStyle]'
 })
export class MyStyleDirective {
@Input('appMyStyle') styleColor:string;
 defaultColor:string='grey';
 constructor(
 private el:ElementRef,
)  {

   }
  ngOnInit(){
 this.el.nativeElement.style.background = "yellow";
 }
 @HostListener('mouseenter')onMouseEnter(){
 this.highlight(this.styleColor||this.defaultColor||'red');
  }
  @HostListener('mouseleave')onMouseLeave(){
this.highlight(null);
  }
  @HostListener('dblclick')onDblClick(){
  this.el.nativeElement.style.display='none';
    }
    private highlight(color:string){
     this.el.nativeElement.style.backgroundColor=color;
    }
   }

在其他组件中调用:

<table class="table">
<div>
<!--<span>{{my_name}}</span>-->
<h1> {{selector_condition_education}}</h1>
<h1>{{selector_condition_time}}</h1>
</div>
<tr>
<th>序号</th>
<th>职位</th>
<th>工资</th>
<th>学历</th>
</tr>
<!--<tr *ngFor="let info of select_position index as i"   
(click)="my_name=info?.name" >-->
<tr *ngFor="let info of select_position index as i" 
(click)="sendData(info?.name)" appMyStyle="blue">
<td>{{i}}</td>
<td>{{info?.name}}</td>
<td>{{info?.salary}}</td>
<td>{{info?.education}}</td>
 </tr>
</table>

主要是 appMyStyle="blue",blue会通过@input传回到指令中,然后通过指令中的@HostListener('mouseenter')onMouseEnter(){ this.highlight(this.styleColor||this.defaultColor||'red'); }
给显示页面添加外观。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容