这是因为Angular v15更改了指令的工作原理。如果您在v15中遇到了指令不起作用的问题,请尝试以下
@Directive({ selector: 'my-custom-element' }) export class MyCustomElementDirective { constructor(element: ElementRef) { element.nativeElement.style.backgroundColor = 'red'; } }
@Directive({ selector: '[myCustomDirective]' }) export class MyCustomDirective { @Input('myCustomDirective') customInput: string;
@HostListener('click') onClick() {
console.log(`Clicked with input ${this.customInput}`);
}
}
import { Directive, ElementRef } from '@angular/core'; import { Ng1DirectiveAdapter } from 'ng-v14-adapters';
@Directive({ selector: '[myCustomDirective]' }) export class MyCustomDirective extends Ng1DirectiveAdapter { link(scope, element) { element.css('background-color', 'red'); } }
无论您选择哪种方案,都应该先仔细查看Angular v15中的指令语法更改,并确定哪些更改可能影响您的现有代码。然后,您可以根据需要进行调整或添加新的指令代码。