Get the width, height and offset of clicked div - Angular 2

前端 未结 2 1893
长发绾君心
长发绾君心 2020-12-21 09:48

I have a template that creates a list of links using *ngFor and a separate div element that I want to change its location based on the currently active link.

相关标签:
2条回答
  • You can use the $event property to handle the width, height, offset and so on. By using this method, a traditional javascript comes into play as below

    HTML code will be as

    <div *ngFor="let link of links;" class="div-link" 
                 height="100px"
                 width="30px"
                 (click)="changeActiveLink($event)">
              <h2>{{link}}</h2>
    </div>
    <div height="height" width="width" id="highlighter">some text</div>
    

    Handling the clicked element from above div element as

    changeActiveLink(value){
        this.height=value.srcElement.parentElement.attributes['height'].value;
        this.width=value.srcElement.parentElement.attributes['width'].value;
        console.log(this.width);
        console.log(this.height); 
      }
    

    Note: In the above example, the click event is on the letter so we will get the srcElement as h2 so I am using the parentElement. In real time you can handle it with either ways having a if condition inside the method.

    You can also console.log the clicked element and get more idea to achieve this.

    LIVE DEMO

    0 讨论(0)
  • 2020-12-21 10:43

    You can place a handle on the element you want to mess with ..

    <div #handle ..>
    

    then in your component class you can access the component using the @ViewChild annotation.

    Then in your ngOnViewInit you can do ..

    ngOnViewInit() {
      viewChildEl.offsetLeft = 100;
    }
    

    Should point you in the right direction.

    0 讨论(0)
提交回复
热议问题