Home > Net >  Script works in index.html and style.css, but not my angular component
Script works in index.html and style.css, but not my angular component

Time:03-18

<script>
  var slider = document.getElementById('slider');
  var active = document.getElementById('active');
  var line1 = document.getElementById('line1');
  var line2 = document.getElementById('line2');

  line1.onclick = function() {
    slider.style.transform = 'translateX(0)';
  }
  line2.onclick = function() {
    slider.style.transform = 'translateX(-50%)';
  }
</script>

I am using angular, and I have this script here inside a file I have called home.component.html. This script is supposed to shift this text I have left and right. However, the script doesn't work and I guess the home.component.css isn't being influenced? I came to this conclusion by copy and pasting all the code i have in my home component's html and css file into index.html and style.css. For some reason though, the script works and the text moves left and right. What's the exact issue here, and why doesn't it work inside of an angular component?

CodePudding user response:

If you'd want to include scripts via <script> tag in an angular project you'd need to add the scripts in <head> part of index.html. But that is bad practice. Better way would to be import scripts via angular.json. But even then your script would not work as it is. Because component gets compiled after scripts are run. So your script will not getElementById because there ain't not elements to get at a time when scripts will be run.

Here's an alternative example:

<div #line1 style="width: 100px; height: 10px; background-color: red" (click)="onTranslatePos(line1)"></div>
  onTranslatePos(item: HTMLElement) {
    item.style.transform = 'translateX(-50%)';
  }

Working example: https://stackblitz.com/edit/angular-ivy-4rzqkw?file=src/app/app.component.html

CodePudding user response:

Why not use Angular?

<div  [style.transform]="'translateX(' value ')'">
   ..
</div>
<button  (click)="value='0'">click</button>
<button  (click)="value='-50%'">click</button>

//in .ts you declare
value:string='0'

Remember: Angular is MVW: you has variables in your .ts that can change, you use this variables to change the properties of the elements of .html and use events to change the variables

  • Related