Я получаю ошибку ниже для директивы. Я просто хочу показать цвет при наведении курсора на текст.
лучше 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);
}
}
основные-выделить-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>