指令可以理解为没有模板的组件,它需要一个宿主元素
推荐使用方括号 [] 指定Selector,使它变成一个属性
html
<div appGridItem *ngFor="let item of channels">
<img [src]="item.icon" alt="" [appGridItemImage]='"4rem"' [fitMode]="'none'">
<span appGridItemTitle>{{ item.title }}</span>
</div>
ts
import { Component, OnInit} from '@angular/core';
export interface Channel {
id: number;
icon: string ;
title: string;
link: string;
}
@Component({
selector: 'app-horizontal-grid',
templateUrl: './horizontal-grid.component.html',
styleUrls: ['./horizontal-grid.component.css']
})
export class HorizontalGridComponent implements OnInit {
channels:Channel[]=[
{
id:1,
icon:'../../../../assets/images/banner/banner1.jpg',
title:'限时秒杀',
link:''
},
{
id:2,
icon:'../../../../assets/images/banner/banner1.jpg',
title:'断码清仓',
link:''
}
]
constructor() { }
ngOnInit() {
}
}
指令
drid-item-image.directive.ts
import { Directive, ElementRef, Renderer2, Input } from '@angular/core';
@Directive({
selector: '[appGridItemImage]',
})
export class GridItemImageDirective {
@Input() appGridItemImage = '2rem';
@Input() fitMode = "cover"
constructor(private elr:ElementRef, private rd2:Renderer2){
}
ngOnInit(): void {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
this.rd2.setStyle('grid-area','image')
this.rd2.setStyle('width',this.appGridItemImage)
this.rd2.setStyle('height',this.appGridItemImage)
this.rd2.setStyle('object-fit',this.fitMode)
}
}
grid-item-title.directive.ts
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appGridItemTitle]',
})
export class GridItemTitleDirective {
constructor(private elr:ElementRef, private rd2:Renderer2){
}
ngOnInit(): void {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
this.rd2.setStyle('grid-area','title')
}
}
grid-item.directive.ts
import { Directive, ElementRef, Renderer2,HostBinding } from '@angular/core';
@Directive({
selector: '[appGridItem]',
})
export class GridItemDirective {
constructor(private elr:ElementRef, private rd2:Renderer2){
}
ngOnInit(): void {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
this.rd2.setStyle('display','grid')
this.rd2.setStyle('grid-template-areas',`'image' 'title'`)
this.rd2.setStyle('place-items','center')
this.rd2.setStyle('width','4.3rem')
}
}
指令没有模板,指令要寄宿在一个元素之上 - 宿主(Host)
@HostBinding 绑定宿主的属性或者样式
@HostListener 绑定宿主的事件
组件的样式中也可使用:host这样一个伪类选择器
:host{
display: flex;
justify-content: center;
}
代表本身的样式
@HostListener("click",["$event.target"])
handleClick(ev){
console.log(ev)
}