Загрузка…
Загрузка…
В Angular три основных вида директив:
@Component). Самый частый вид.*ngIf, *ngFor, @if/@for в новых контрол-флоу, кастомные с TemplateRef + ViewContainerRef).NgClass, NgStyle, кастомные @Directive с @HostBinding / @HostListener).@Directive({
selector: '[appHighlight]',
standalone: true,
})
export class HighlightDirective {
private el = inject(ElementRef<HTMLElement>);
@Input('appHighlight') color = 'yellow';
@HostListener('mouseenter') onEnter() {
this.el.nativeElement.style.backgroundColor = this.color;
}
@HostListener('mouseleave') onLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}<p appHighlight="lightblue">Текст</p>Структурные обычно используют синтаксис * (микросинтаксис) или явный ng-template. Компонент формально тоже директива, но с template и styles.
На собеседовании полезно добавить: директива без шаблона = attribute/structural; с шаблоном = component; селектор может быть attribute, class, element. Умение написать простую attribute-директиву — частый practical follow-up.
