
이전 기사에서는 Angular 에 대한 개요를 설명했습니다. 사용자 지정 지침 부분에서는 이를 작성할 수 있었지만 실제 시나리오에서는 여전히 표준화된 관리가 필요합니다.
Angular는 Angular.js의 업그레이드 버전입니다. [추천 관련 튜토리얼: "Angular Tutorial"]
그래서 이번 글에서는 Tooltip 활용하여 Custom Instruction의 내용을 설명하겠습니다.
온라인 렌더링은 다음과 같습니다.

디렉터리 구조는
이전 기사에서 구현한 코드 프로젝트를 기반으로 합니다. 명령줄을 실행합니다.
# 지시문 폴더를 입력합니다. $ cd directives #툴팁 폴더 생성$ mkdir 툴팁 # 툴팁 폴더에 들어가세요. $ cd tooltip # 툴팁 구성 요소 생성 $ ng 구성 요소 툴팁 생성 # Create tooltip directive $ ng generate directive tooltip위 명령줄을 실행하면 다음과 같은 app/directive/
tooltip
app/directive/tooltip 디렉터리 구조를 얻게 됩니다.
├── 툴팁 // 툴팁 구성 요소 │ ├── user-list.comComponent.html // 페이지 뼈대 │ ├── user-list.comComponent.scss // 페이지 고유 스타일 │ ├── user-list.comComponent. .ts // 테스트 파일 │ └── user-list.comComponent.ts // javascript 파일 ├── tooltip.directive.spec.ts // 테스트 파일 └── tooltip.directive.ts // 디렉티브 파일
자, 여기 주로 관리를 용이하게 하기 위해 구성요소를 tooltip 과 동일한 수준에 배치했습니다. 물론 이것은 사람마다 다르므로 공용 components 폴더에 넣을 수 있습니다.
html 파일에
툴팁 구성 요소를 작성합니다
:<div class="caret"></div>
<div class="tooltip-content">{{data.content}}</div> 스타일 파일 .scss에는 $black: #000000;
.scss 있습니다
$화이트: #ffffff;
$캐럿 크기: 6px;
$tooltip-bg: transparentize($black, 0.25); // 투명화는 sass의 구문입니다. $grid-gutter-width: 30px;
$body-bg-color: $white;
$app-anim-시간: 200ms;
$app-anim-curve: 완화;
$std-국경-반경: 5px;
$zindex-최대: 100;
// :host 의사 클래스 선택기, 구성요소 요소 자체의 스타일을 설정합니다.
위치: 고정;
패딩: $grid-gutter-width/3 $grid-gutter-width/2;
배경색: $tooltip-bg;
색상: $body-bg-color;
불투명도: 0;
전환: 모든 $app-anim-time $app-anim-curve;
텍스트 정렬: 중앙;
국경 반경: $std-경계 반경;
z-색인: $zindex-max;
}
.caret { // 캐럿 너비: 0;
높이: 0;
테두리 왼쪽: 6px 투명 투명;
테두리 오른쪽: 6px 솔리드 투명;
테두리 하단: 6px 솔리드 $tooltip-bg;
위치: 절대;
상단: -$캐럿 크기;
왼쪽: 50%;
여백 왼쪽: -$caret-size/2;
테두리 하단 색상: $tooltip-bg;
} 흠~
css마법같은 것인데,sass관련 내용을 설명하는 글을 준비하겠습니다...
그러면 javascript 파일 tooltip.component.ts 의 내용은 다음과 같습니다.
import {
요소,
ElementRef, //요소는 HostBinding을 가리킵니다.
파괴시,
OnInit
} '@angular/core'에서;
@요소({
selector: 'app-tooltip', // 내 구성 요소가 무엇인지 나타내는 식별자, 여기 app-tooltip이 있습니다.
templateUrl: './tooltip.comComponent.html', // 이 구성 요소의 뼈대 styleUrls: ['./tooltip.comComponent.scss'] // 이 구성 요소의 비공개 스타일})
내보내기 클래스 TooltipComponent는 OnInit를 구현합니다.
public data: any; // 지시문에 값을 할당합니다. private displayTimeOut: any;
// 컴포넌트 자체의 호스트 바인딩과 관련된 데코레이터 @HostBinding('style.top') hostStyleTop!: string;
@HostBinding('style.left') HostStyleLeft!: 문자열;
@HostBinding('style.opacity') hostStyleOpacity!: 문자열;
건설자(
비공개 요소Ref: ElementRef
) { }
ngOnInit(): 무효 {
this.hostStyleTop = this.data.elementPosition.bottom + 'px';
if(this.displayTimeOut) {
클리어타임아웃(this.displayTimeOut)
}
this.displayTimeOut = setTimeout((_: any) => {
// 여기에서 툴팁과 왼쪽 사이의 거리를 계산합니다. 계산 공식은 다음과 같습니다. tooltip.left + 대상 요소의 .width - (tooltip.width/2)
this.hostStyleLeft = this.data.elementPosition.left + this.data.element.clientWidth / 2 - this.elementRef.nativeElement.clientWidth / 2 + 'px'
this.hostStyleOpacity = '1';
this.hostStyleTop = this.data.elementPosition.bottom + 10 + 'px'
}, 500)
}
// 컴포넌트가 파괴되었습니다 ngOnDestroy() {
// 구성 요소가 삭제된 후 타이머를 지워 메모리 누수를 방지합니다. if(this.displayTimeOut) {
클리어타임아웃(this.displayTimeOut)
}
}
} 툴팁 지침 작성이
이번 글의 초점이 됩니다. 구체적인 지침을 코드에 표시하겠습니다~
관련 파일 tooltip.directive.ts 의 내용은 다음과 같습니다.
import {
ApplicationRef, // 전역 호출 감지 ComponentFactoryResolver, // 컴포넌트 객체 생성 ComponentRef, // ComponentFactory 지시문에 의해 생성된 요소를 가리키는 컴포넌트 인스턴스의 연결 및 안내, ElementRef,
EmbeddedViewRef, // EmbeddedViewRef는 ViewRef에서 상속되며 템플릿 요소에 정의된 UI 요소를 나타내는 데 사용됩니다.
HostListener, // DOM 이벤트 수신 Injector, // 종속성 주입 입력
} '@angular/core'에서;
import { TooltipComponent } from './tooltip/tooltip.comComponent';
@지령({
선택기: '[appTooltip]'
})
내보내기 클래스 TooltipDirective {
@Input("appTooltip") appTooltip!: 문자열;
전용 구성요소Ref!: ComponentRef<TooltipComponent>;
// 왼쪽, 오른쪽, 위쪽, 아래쪽 등 대상 요소의 상대 위치를 가져옵니다.
요소 위치()를 얻습니다.
this.elementRef.nativeElement.getBoundingClientRect()를 반환합니다.
}
건설자(
보호된 elementRef: ElementRef,
보호된 appRef: ApplicationRef,
보호된 컴포넌트FactoryResolver: ComponentFactoryResolver,
보호된 인젝터: 인젝터
) { }
//툴팁 생성
보호된 createTooltip() {
this.comComponentRef = this.comComponentFactoryResolver
.resolveComponentFactory(TooltipComponent) // 툴팁 바인딩 컴포넌트.create(this.injector);
this.comComponentRef.instance.data = { // 데이터 데이터 콘텐츠 바인딩: this.appTooltip,
요소: this.elementRef.nativeElement,
요소 위치: this.elementPosition
}
this.appRef.attachView(this.comComponentRef.hostView); //뷰 추가 const domElem = (this.comComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
document.body.appendChild(domElem);
}
// 툴팁 삭제
보호된 destroyTooltip() {
if(this.comComponentRef) {
this.appRef.detachView(this.comComponentRef.hostView); // 뷰 제거 this.comComponentRef.destroy();
}
}
// @HostListener('mouseover')로의 마우스 움직임을 수신합니다.
OnEnter() {
this.createTooltip();
}
// 마우스 움직임을 수신합니다. out@HostListener('mouseout')
온아웃() {
this.destroyTooltip();
}
} 이제 함수의 99% 완료되었습니다. 이제 페이지에서 호출할 수 있습니다.
페이지에서
user-list.component.html 에 다음 콘텐츠를 추가하도록 호출합니다.
<p style="margin-top: 100px;">
<!-- [appTooltip]="'Hello Jimmy'"가 핵심입니다-->
<스팬
[appTooltip]="'안녕하세요 지미'"
style="margin-left: 200px; 너비: 160px; text-align: center; padding: 20px 0; display: inline-block; border: 1px solid #999;"
>지미</span>
</p> app.module.ts 에 TooltipDirective 명령을 선언했으며 이를 직접 호출할 수 있습니다. 현재 효과는 다음과 같습니다.

우리가 구현한 tooltip 하단 중앙에 표시되는데, 이는 angular ant design 에서 tooltip 의 bottom 속성과 같이 우리가 일반적으로 프레임워크를 사용하는 것입니다. 다른 속성의 경우 독자가 관심이 있으면 확장할 수 있습니다.
이 시점에서 우리는 우리가 작성한 지침 파일을 잘 유지할 수 있습니다.