与DOM分离并将功能引入指令

时间:2018-07-05 18:58:48

标签: angular typescript angular-directive

我正在尝试制定“对齐组件”指令。在这一点上,我已经使用驻留在应用程序组件中的逻辑进行了概念验证(可能会被Renderer2 HostListeners和HostBindings替换),并且看起来我必须获得dom属性(child1L,child1R ...等) 。)可能使用Renderer2的孩子。我的问题是,您如何将到目前为止所做的工作分解为一个指令或一组父子指令?或者至少您将从这里走什么方向?我是Renderer2,HostListeners和HostBinding的新手,所以我想知道有经验的人如何做到这一点。谢谢。这是我的current stackblitz.

app.component.ts:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

switchDirection = "first";
head: ElementRef;

@ViewChild('child01') child01;
@ViewChild('child02') child02;
@ViewChild('child03') child03;

  onScroll(event: Event) {
    let viewBoundaryL = (event.target as HTMLElement).scrollLeft;
    console.log("viewBoundaryL:" + viewBoundaryL);

//SNAP FROM FIRST TO SECOND CHILD
    if(viewBoundaryL >= 50 && this.switchDirection === "first"){
this.child02.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
     this.switchDirection = "second";
      //  console.log(this.switchDirection)
    }, 300);
    }

//SNAP FROM SECOND TO FIRST CHILD
    if(viewBoundaryL <= 310 && this.switchDirection === "second"){
this.child01.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
  this.switchDirection = "first";
  // console.log(this.switchDirection)
    }, 300);
    }

//SNAP FROM SECOND TO THIRD CHILD
        if(viewBoundaryL >= 370 && this.switchDirection === "second"){
this.child03.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
  this.switchDirection = "third";
  // console.log(this.switchDirection)
    }, 300);
  }

//SNAP FROM THIRD TO SECOND CHILD
        if(viewBoundaryL <= 615 && this.switchDirection === "third"){
this.child02.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
  this.switchDirection = "second";
  // console.log(this.switchDirection)
    }, 300);
        }     
  }
}

app.component.html:

 <div class="container"  (scroll)="onScroll($event)" >

<child1 #child01></child1>
<child2 #child02></child2>
<child3 #child03></child3>

</div>

感谢您的见解!

1 个答案:

答案 0 :(得分:1)

您可能想创建一个attribute directive

您可以使用Angular CLI通过以下命令轻松创建directive(您可以提供路径,其名称为 core / directives / my-directive-name ):< / p>

ng generate directive <name-of-directive>

然后在构造函数中,可以添加以下内容以获得对元素的引用。

el: ElementRef

最后使用HostListener或任何绑定到滚动事件的技术。您可以调用对元素代码捕捉的调用(必须更改为仅检查自身),然后元素将检查自身是否需要启动滚动。如果符合条件,就可以。

要获得更多积分,您可以添加输入进行设置,例如,何时捕捉到元素,带有指令的模板将如下所示:

<div [myDirective] [scrollAt]="300"></div>

然后在指令本身中,您将拥有:

@Input() scrollAt: number = 300 // sets a default incase it isn't provided;

然后,您可以将此变量用作视图边界。

希望这会有所帮助,或者至少会让您走上正轨!