更新时间:2023-02-12 08:29:05
您的代码存在一些问题.
There are a few issues with your code.
只需将 adjustSide
用作 @Input
别名,这样就不必在指令中声明其他属性.
Just use the adjustSide
as an @Input
alias so that you don't have to declare other properties on your directive.
只需像这样使用它:
<div class="wrapper">
<div class="app-menu" [adjustSide]="position">
<router-outlet></router-outlet>
</div>
</div>
指令应如下所示:
import { Directive, ElementRef, Renderer2, Input, OnChanges } from '@angular/core';
@Directive({
selector: '[adjustSide]'
})
export class AdjustSizeDirective implements OnChanges {
@Input('adjustSide') side: string;
constructor(
private el: ElementRef,
private renderer: Renderer2
) { }
ngOnChanges() {
console.log('Side changed to : ', this.side);
if (this.side == 'left') {
this.renderer.addClass(this.el.nativeElement, 'offset-left');
this.renderer.removeClass(this.el.nativeElement, 'offset-right');
}
else{
this.renderer.removeClass(this.el.nativeElement, 'offset-left');
this.renderer.addClass(this.el.nativeElement, 'offset-right');
}
}
}
如果您查看控制台,将会看到 ngOnChanges
被调用.我已经通过它记录了 this.side
的值.
If you have a look at the console, you'll see the ngOnChanges
getting called. I've logged the value of this.side
through that.
这是 StackBlitz示例您的情况.