2017-11-22 5 views
0

ウィンドウの幅を700px以上にすると、要素を隠すべきディレクティブ(カスタム* ngIf)があります。私はウィンドウのサイズを変更すると私のデジェクティブは更新されず、要素は隠されませんが、常にthis.widthが更新されます。どのように修正できるか考えてみましょうか?次に例を示します。角度2 - ウィンドウのサイズを変更したときのディレクティブの更新

import { Directive, Input, TemplateRef, ViewContainerRef, HostListener,NgZone} from '@angular/core'; 
 

 
@Directive({ 
 
    selector: '[ifViewportSize]' 
 
}) 
 

 
export class ifViewportSize { 
 
    width:number; 
 

 
    constructor(private templateRef: TemplateRef<any>, 
 
    private viewContainer: ViewContainerRef, 
 
    private ngZone:NgZone) { 
 
    this.width = 600; 
 

 
    window.onresize = (e) => { 
 
     this.ngZone.run(() => { 
 
     this.width = window.innerWidth; // WIDTH UPDATING 
 
     }); 
 
    }; 
 
    } 
 

 
    @Input() set ifViewportSize(size: string){ 
 
    if (this.width<700) { 
 
     
 
    // HERE IS NOT UPDATE 
 

 
     this.viewContainer.createEmbeddedView(this.templateRef); 
 
    } else { 
 
     this.viewContainer.clear(); 
 
    } 
 

 
    } 
 
    
 
}

プロジェクトのコードは、これはあなたを助けることができる* ngIf使用せず、ここでstackblitz

答えて

1

さ:

コンストラクタで:

constructor(private element: ElementRef /*other dependencies*/) { 
    // your code here 
} 

短所の外HostListenerとElementRefをインポートするには

@HostListener('window:resize', []) 
onWindowResize(): void { 
    if (window.innerWidth < 700) { 
     this.element.nativeElement.style.display = 'none'; 
    } else { 
     this.element.nativeElement.style.display = 'block'; 
    }; 
} 

:tructorこれを使用

import {ElementRef, HostListener} from '@angular/core'; 

私はこれがあなたを助け願っています。

関連する問題