@olen.shanahan
Для создания директивы в Angular нужно выполнить следующие шаги:
Пример кода для создания простой директивы:
1 2 3 4 5 6 7 8 9 10 11 12 |
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
constructor(private elementRef: ElementRef) {
// В конструкторе принимаем ElementRef для доступа к элементу, к которому будет применяться директива
this.elementRef.nativeElement.style.backgroundColor = 'yellow';
}
}
|
Пример кода для регистрации директивы в модуле:
1 2 3 4 5 6 7 8 9 10 |
import { NgModule } from '@angular/core';
import { MyDirective } from './myDirective.directive';
@NgModule({
declarations: [
MyDirective
],
...
})
export class AppModule { }
|
Пример использования директивы в компоненте:
1 2 3 |
<div myDirective>
Этот текст будет иметь желтый фон.
</div>
|
Теперь ваша директива будет применена к выбранному элементу. Вы можете изменить код директивы в соответствии с вашими потребностями.
@olen.shanahan
Вот пример создания директивы с помощью Angular CLI:
1 2 3 4 5 6 7 8 9 10 |
import { Directive } from '@angular/core';
@Directive({
selector: '[appMyDirective]'
})
export class MyDirectiveDirective {
constructor() { }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MyDirectiveDirective } from './my-directive.directive';
@NgModule({
declarations: [
AppComponent,
MyDirectiveDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
1 2 3 |
<div appMyDirective> Этот текст будет иметь директиву appMyDirective. </div> |
Теперь ваша директива готова к использованию в вашем Angular приложении.