Angular 6自定义指令在值更改后不更新 [英] Angular 6 custom directive not updating after value change
问题描述
我想制作一个动态菜单,菜单本身具有css类,如果我选中一个复选框,则菜单必须从左向右更改位置.
I want to make a dynamic menu, the menu itself has css class in which if i check a checkbox the menu has to change position from left to right.
现在,该指令有效,但只有一次,当程序加载时,如果我尝试更改程序中的复选框,则不会发生任何事情.
Right now the directive works, but only once, when the program loads, if i try to change the check the checkbox within the program nothing happens.
html:
<div class="wrapper">
<div class="app-menu" adjustSide side="{{position}}">
<router-outlet></router-outlet>
</div>
</div>
我尝试了(side)="position"
, [side] ="position"
和 [(side)] ="position" 代码>.
和指令:
@Input('side') private side:string;
private el: HTMLInputElement;
constructor( private renderer: Renderer2, private elementRef: ElementRef ) {
this.el = this.elementRef.nativeElement;
}
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
if (this.side == 'left') {
this.renderer.addClass(this.el, 'offset-left');
this.renderer.removeClass(this.el, 'offset-right');
}else{
this.renderer.removeClass(this.el, 'offset-left');
this.renderer.addClass(this.el, 'offset-right');
}
}
我仍在学习有角度的知识,因此由于某些原因,我不明白为什么新值似乎没有达到指令,但我不知道为什么.
I'm still learning angular, so for some reason i don't understand why it seems the new value doesn't reach to the directive, but i have no idea why.
我做错了什么?我错过了什么吗?
What i'm doing wrong? did i missed something?
推荐答案
您的代码存在一些问题.
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示例您的情况.
这篇关于Angular 6自定义指令在值更改后不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!