C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Angular 7 DirectivesDirectives are instructions in the DOM. They specify how to place your components and business logic in the Angular. Directives are js class and declared as @directive. There are 3 directives in Angular.
Component Directives: Component directives are used in main class. They contain the detail of how the component should be processed, instantiated and used at runtime. Structural Directives: Structural directives start with a * sign. These directives are used to manipulate and change the structure of the DOM elements. For example, *ngIf and *ngFor. Attribute Directives: Attribute directives are used to change the look and behavior of the DOM elements. For example: ngClass, ngStyle etc. Difference between Attribute Directive and Structural Directive
How to create custom Directives?
You can create your own custom directives to use in Angular components. Create a basic attribute directiveYou have seen the attribute directive like ngClass and ngStyle. Now, it's time to create our own attribute directives. First, create a folder. Let's name it "simple-style". Then, create a file within that folder named as "simple-style.directive.ts"
import {Directive, ElementRef, OnInit} from '@angular/core';
@Directive( {
selector: '[appSimpleStyle]'
})
export class SimpleStyleDirective implements OnInit {
constructor(private elementRef: ElementRef) {
}
ngOnInit() {
this.elementRef.nativeElement.style.backgroundColor = 'green';
}
Now, you have to inform Angular that you have a new directive. So, you have to add SimpleStyleDirective to app.module.ts and also import it.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {SimpleStyleDirective} from './simple-style/simple-style.directive';
@NgModule({
declarations: [
AppComponent,
SimpleStyleDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now, your directive is created. Let's check it. Open app.component.html and use your created SimpleStyleDirective <p appSimpleStyle>Style me with your created SimpleStyleDirective</p> |