【发布时间】:2023-04-09 12:04:01
【问题描述】:
我想创建一个可以检测浏览器高度和宽度变化的自定义指令。
我的指令:
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>
我做错了吗?无论如何我可以修改此指令以使其侦听浏览器屏幕尺寸的变化吗?
【问题讨论】:
-
Angular 指令只能在 Angular 组件的模板中工作。 Angular 组件只能在其他 Angular 组件中使用,
bootstrap: [...]或 app-module 中列出的组件除外。 -
嗨@GünterZöchbauer,我也尝试将指令更改为app.component.html,但它不起作用。我还有什么遗漏吗?
-
不知道您所说的“也尝试过”是什么意思。也许您可以用您“也尝试过”的内容来更新您的问题。如果你想在不是用 Angular 构建的页面中到处添加一些 Angular 的东西,Angular 可能不适合你。
-
你检查过指令的构造函数是否被调用了吗?
-
您的代码看起来不错。大小已更改并显示在控制台中。 Plnkr.
标签: angular angular2-directives