我的指令出现错误。我只是想在悬停文字时显示颜色。
better-highlight.directive.ts
import { Directive, OnInit, ElementRef, HostListener, Renderer2 } from '@angular/core';
@Directive({
selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective implements OnInit{
constructor(private elRef: ElementRef, private rederer: Renderer2) { }
ngOnInit() {
// this.rederer.setStyle(this.elRef.nativeElement, 'background-color', 'blue', false, false);
}
@HostListener('mouseenter') mouseOver(eventData: Event) {
this.rederer.setStyle(this.elRef.nativeElement, 'background-color', 'blue', false, false);
}
@HostListener('mouseenter') mouseleave(eventData: Event) {
this.rederer.setStyle(this.elRef.nativeElement, 'background-color', 'transparent', false, false);
}
}
basic-highlight-directive.ts
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appBasicHighlight]'
})
export class BasicHighLightDirective implements OnInit {
constructor(private elementRef: ElementRef) {
}
ngOnInit(){
this.elementRef.nativeElement.style.backgroundColor = 'green';
}
}
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
oddNumbers = [1, 3, 5];
evenNumbers = [2, 4];
onlyOdd = false;
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BasicHighLightDirective } from './basic-highlight/basic-highlight-directive';
import { BetterHighlightDirective } from './better-highlight/better-highlight.directive';
@NgModule({
declarations: [
AppComponent,
BasicHighLightDirective,
BetterHighlightDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<div class="container">
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary" (click)="onlyOdd = !onlyOdd">Show Numbers</button>
<br><br>
<ul class="list-group">
<div *ngIf="onlyOdd">
<li class="list-group-item"
[ngClass]="{odd: odd % 2 !== 0}"
[ngStyle]="{backgroundColor: even % 2 !== 0 ? 'yellow' : 'transparent'}"
*ngFor="let odd of oddNumbers">
{{ odd }}
</li>
</div>
<div *ngIf="!onlyOdd">
<li class="list-group-item"
[ngClass]="{odd: even % 2 !== 0}"
[ngStyle]="{backgroundColor: even % 2 !== 0 ? 'yellow' : 'transparent'}"
*ngFor="let even of evenNumbers">
{{ even }}
</li>
</div>
</ul>
<p appBasicHighlight>Style me with basic directive!</p>
<p appBetterHighlight>Style me with a Better directive!</p>
</div>
</div>
</div>
答案 0 :(得分:0)
您好,您使用的是setStyle错误。
this.rederer.setStyle(this.elRef.nativeElement, 'background-color', 'blue');
只有4个参数而不是5个。 https://angular.io/api/core/Renderer2#setStyle
抽象setStyle(el:任意,样式:字符串,值:任意,标志?:RendererStyleFlags2):无效 参数
1]任何 元素。
2]样式字符串
样式的名称。
3]值任何 新值。
4]可选标志RendererStyleFlags2 样式变化的标志。默认情况下未设置任何标志。
可选。默认值为未定义。