Reputation: 5
StackBlitz - https://angular-hof8w9.stackblitz.io
Custom Directive
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appBorder]',
})
export class BorderDirective {
@Input('appBorder') borderColor!: string;
defaultColor: string = 'black';
constructor(private el: ElementRef) {
this.applyBorder(this.borderColor || this.defaultColor);
}
applyBorder(color: string): void {
console.log(this.borderColor); // Undefined
this.el.nativeElement.style.border = `5px solid ${color}`;
}
}
app.module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { BorderDirective } from './border.directive';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, HelloComponent, BorderDirective],
bootstrap: [AppComponent],
})
export class AppModule {}
app.component.html
<div [appBorder]="color" style="height: 100px"></div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
color: string = 'red';
}
The border of the div should be red but is being defaulted to black (specified in the directive) because the @Input() is undefined. Thanks in advance.
Upvotes: 0
Views: 58
Reputation: 51
You can't access the property on your constructor, it hasn't been initialized yet. Try using ngOnInit()
instead.
Working example: https://stackblitz.com/edit/angular-ul2vp5?file=src/app/directive/border.directive.ts
Upvotes: 1