实现自己的* ngIf

时间:2017-09-15 11:01:41

标签: angular angular2-directives angular-ng-if elementref

我想创建自己的* ngIf指令。该指令将获得一个数字,如果屏幕内部宽度像素小于它得到的数字,它将不会渲染模板。

如何实现自己的* ngIf?

2 个答案:

答案 0 :(得分:2)

它被称为结构指令。

您可以查看source of *ngIf

Angular文档中还有一节介绍https://angular.io/guide/structural-directives

主要部分是

 this.viewContainer.createEmbeddedView(this.templateRef);

允许标记模板。

如果你有

<my-component *myIf="isTrueOrFalse"></my-component>

*将导致

<my-component></my-component>

作为模板传递给指令,然后可以标记/删除。

答案 1 :(得分:0)

这很简单。

使用好的ngIf,例如此*ngIf='someVariable',然后只需将someVariabletrue切换为false,就可以将其渲染或不

我要做的是在组件中创建一个侦听窗口宽度事件的事件监听器,通过设置someVariable

来查看宽度将决定是否隐藏某个元素