美文网首页我爱编程
Angular之自定义指令

Angular之自定义指令

作者: writeanewworld | 来源:发表于2018-01-30 18:35 被阅读0次

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'); }
给显示页面添加外观。

相关文章

网友评论

    本文标题:Angular之自定义指令

    本文链接:https://www.haomeiwen.com/subject/bqoczxtx.html