in this tutorial
https://www.tektutorialshub.com/angular/custom-directive-in-angular/
the directive works as expected. however i would like to display the value of the color set on the console via
console.log
please have a look at my attempt in the code posted below, i used
console.log(this.ttClass);//<---my attempt. it did not work
inside OnInit() but it did not work
please let me know how to display the value of the color from the css file on the console
app.component.ts :
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ngDirective2';
}
tt-class.directive.ts :
import { Directive, ElementRef, Input, OnInit } from '@angular/core'
@Directive({
selector: '[ttClass]'
})
export class TtClassDirective implements OnInit{
@Input()
ttClass : string ="";
ngOnInit() {
this.el.nativeElement.classList.add(this.ttClass);
console.log(this.ttClass);//<---my attempt. it did not work
}
constructor(private el: ElementRef) { }
}
app.coponent.html :
<button [ttClass]="'blue'">Click Me</button>
app.coponent.css :
.blue {
background-color: lightblue;
}
app.component.html :
<h1 my-error>Hello {{name}}</h1>
<h2 *myCustomIf="condition">Hello {{name}}</h2>
<button (click)="condition = !condition">Click</button>
image :
Working solution: https://stackblitz.com/edit/angular-jcia4c?file=src%2Fapp%2Ftt-class.directive.ts
Also, styles should ALWAYS
be modified via Renderer2
in angular and not by directly accessing the nativeElement
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.