First and second directives have been created for a basic CLI framework. The HomePageModule includes the home-page component along with MyFirst.directive.ts, which is referenced in home-page.component.html successfully.
MySecond.directive.ts is similar to MyFirst but at the app.component level. It is declared in app.module.ts, however, it cannot be referenced in home-page.component.html.
The AppModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {HomePageModule} from './home-page/home-page.module';
import {MySecondDirective} from './MySecond.directive';
@NgModule({
declarations: [
AppComponent,
MySecondDirective
],
imports: [
BrowserModule,
AppRoutingModule,
HomePageModule
],
providers: [],
exports: [MySecondDirective],
bootstrap: [AppComponent]
})
export class AppModule { }
Home Page Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomePageComponent } from './home-page/home-page.component';
import {MyFirstDirective} from './home-page/MyFirst.directive';
@NgModule({
imports: [
CommonModule
],
declarations: [
HomePageComponent,
MyFirstDirective
],
exports: [
HomePageComponent,
MyFirstDirective
]
})
export class HomePageModule { }
Home Page HTML
<p>
home-page works!
</p>
<div>
<h1 myfirst>TESTING</h1>
<h3 mysecond>Again</h3>
</div>
Program Output https://i.sstatic.net/AQxN5.jpg
Program Structure https://i.sstatic.net/9Dy7X.jpg
MyFirstDirective:
import {Directive, ElementRef, Renderer2} from '@angular/core';
@Directive({
selector: '[myfirst]'
})
export class MyFirstDirective {
constructor(private elementRef: ElementRef, private renderer: Renderer2) {
const nativeElement = elementRef.nativeElement;
this.renderer.setStyle( nativeElement, 'color', 'red');
this.renderer.setStyle( nativeElement, 'background-color', 'yellow');
this.renderer.setStyle( nativeElement, 'border', '1px solid green');
}
}
MySecondDirective:
import {Directive, ElementRef, Renderer2} from '@angular/core';
@Directive({
selector: '[mysecond]'
})
export class MySecondDirective {
constructor(private elementRef: ElementRef, private renderer: Renderer2) {
const nativeElement = elementRef.nativeElement;
this.renderer.setStyle( nativeElement, 'color', 'green');
this.renderer.setStyle( nativeElement, 'background-color', 'orange');
this.renderer.setStyle( nativeElement, 'border', '2px solid red');
}
}
Thank you! - Chuck