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...";
}
})
};
}