Angular 2:自定义指令,用于检测屏幕大小调整

时间:2017-05-22 08:08:46

标签: angular angular2-directives

我想创建一个自定义指令,可以检测浏览器高度和宽度的变化。

我的指示:

        import { Directive, ElementRef, Input, NgZone} from '@angular/core';

        @Directive({ selector: '[resize]' })
        export class ResizeDirective {
            constructor(private ngZone: NgZone) {
                window.onresize = (e) => {
                    //ngZone.run will help to run change detection
                    this.ngZone.run(() => {
                        console.log("Width: " + window.innerWidth);
                        console.log("Height: " + window.innerHeight);
                    });
                };
            }
        }

app.module.ts:

            import { NgModule, CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';


            import { BrowserModule } from '@angular/platform-browser';
            import { ResizeDirective } from './resize.directive';

            @NgModule({
                imports: [
                    BrowserModule,
                    FormsModule,
                ],
                declarations:
                [AppComponent, ResizeDirectiv],               
                bootstrap: [AppComponent],
                schemas: [CUSTOM_ELEMENTS_SCHEMA]

            })

我已将我的指令放在app.component.html的Body标记内。因此,每当浏览器屏幕大小发生变化时,我都需要执行特定的操作。

app.component.html

            <div class="outterContainer" style="width:100%;height:100%;"  resizePlugin>
            <div id="header1" class="header">


            </div>

            <div id="contentSection" class="content">
            <div>
                <div>Resize Demo</div>
                <input [(ngModel)]="studname">{{studname}}
                <createProject></createProject>
                <AddEvent></AddEvent>
                <h2>NavBar + Routing + DragAndDrop + ModalPopup + ReAgrrange Demo</h2>',

            </div>  

            <div>
                <div>
                    <h2>NavBar + Routing + DragAndDrop + ModalPopup Demo</h2>
                    <navbar></navbar>
                    <router-outlet></router-outlet>
                </div>
            </div>
            </div>
            </div>

我做错了吗?无论如何,我可以修改此指令,使其监听浏览器屏幕大小的变化吗?

2 个答案:

答案 0 :(得分:0)

您的指令可能看起来有问题。 angular不会监听你直接传递的事件angular有一个装饰器来监听@HostListener事件。请尝试以下可能对您有帮助的代码

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

    @Directive({ selector: '[resize]' })
    export class ResizeDirective {
        constructor(private ngZone: NgZone) {}
        @HostListener('window:resize', ['$event'])
        onResize(event){
                //ngZone.run will help to run change detection
                this.ngZone.run(() => {
                    console.log("Width: " + window.innerWidth);
                    console.log("Height: " + window.innerHeight);
                });
        }
    }

答案 1 :(得分:-1)

您已经在app.component.html中编写了 ResizeDirectiv ,但是在声明 ResizeDirectiv' e '的末尾还有一个附加的e。在您的app.module.ts中

它们必须相同才能映射。