Home > front end >  How to make in angular your component.ts load after body loads (no external files)
How to make in angular your component.ts load after body loads (no external files)

Time:08-08

i want to add, addEventlister to my id created with uuid, but it giving me back error Cannot read properties of null (reading 'addEventListener')

export class CommentItemComponent implements OnInit {
  textReviewId: string;
  readMoreId: string;
  constructor() {  
    this.textReviewId = uuid();  
    this.readMoreId = uuid();  
}  
 


  ngOnInit(): void {
      var textReview = document.getElementById(this.textReviewId);
      var readMore = document.getElementById(this.readMoreId);
     
        window.onload=function(){
          readMore!.addEventListener('click',function(){
              if(textReview!.classList.contains('text-truncate')){
                  textReview!.classList.remove('text-truncate');
                  readMore!.innerHTML = "Read less";
                  console.log("jestes zjebem");
              }else{
                textReview?.classList.add('text-truncate');
                readMore!.innerHTML = "Read more...";

              }
          })
          };
    


  } ```

CodePudding user response:

put the code inside ngAfterViewInit and remove window.onload:

console.log(this.readMoreId);

var textReview = document.getElementById(this.textReviewId);
var readMore = document.getElementById(this.readMoreId);

readMore!.addEventListener('click',function(){
    if(textReview!.classList.contains('text-truncate')){
        textReview!.classList.remove('text-truncate');
        readMore!.innerHTML = "Read less";
        console.log("jestes zjebem");
    }else{
      textReview?.classList.add('text-truncate');
      readMore!.innerHTML = "Read more...";

    }
})

CodePudding user response:

Put your code inside ngAfterInitView

 ngAfterViewInit() {
   var textReview = document.getElementById(this.textReviewId);
  var readMore = document.getElementById(this.readMoreId);
 
    window.onload=function(){
      readMore!.addEventListener('click',function(){
          if(textReview!.classList.contains('text-truncate')){
              textReview!.classList.remove('text-truncate');
              readMore!.innerHTML = "Read less";
              console.log("jestes zjebem");
          }else{
            textReview?.classList.add('text-truncate');
            readMore!.innerHTML = "Read more...";

          }
      })
      };
}
  • Related