我創建了這個指令來添加一個帶有一些文本的 div,如果用戶懸停在 div 上,我想顯示一個 matTooltoip。如何在運行時將 matTooltips 添加到 div?
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[appTextBlock]'
})
export class MyDirective implements OnInit {
constructor(
private elementRef: ElementRef,
private renderer: Renderer2) { }
ngOnInit(): void { }
public testMethod(toolTip:string){
var pNode = this.renderer.createElement('div');
**//this.renderer.addClass(pNode, 'matTooltip=toolTip' );**
const text = this.renderer.createText('myText');
this.renderer.appendChild(pNode,text);
this.renderer.appendChild(this.elementRef.nativeElement, pNode);
}
uj5u.com熱心網友回復:
首先,您創建如下指令,
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[hintText]',
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@Input()
set hintText(value: string[]) {
this.el.nativeElement.title = value;
}
}
然后在 DOM 元素中使用指令
<div [hintText]="hintText1">Place mouse pointer on me!</div>
<div [hintText]="hintText2">Place mouse pointer on me!</div>
從組件動態更改提示文本,
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
hintText1: string;
hintText2: string;
ngOnInit(): void {
this.hintText1 = 'my text title 1';
this.hintText2 = 'my text title 2';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/352517.html
標籤:有角的
上一篇:更改路由時更改ngOnInit中的元素不起作用,但可以訪問元素
下一篇:帶有路由到組件的角度材料步進器
