0

I created a component that should display videos based on properties that are passed to it in input... it works for me if I insert static data, but with the switch no!

 export class VideoComponent implements OnInit {
   @Input() currentVideo: string | undefined;
   url: any;
   video: any = { id: 'yOYmdyaSOCg' };
   baseUrl: string = 'https://www.youtube.com/embed/';

   constructor(
     private sanitizer: DomSanitizer,
   ) {
     switch (this.currentVideo) {
      case 'foo':
        this.video.id = 'yOYSOCsdsdg';
         break;
       case 'bar':
        this.video.id = '3Z4J_bddKE';
         break;
       case 'foo2':
         this.video.id = 'a8DPNc64';
         break;
       case "bar2":
         this.video.id = 'HZySqMdsclEuSQ';
         break;
       default:
         this.video.id = 'TYYW_WsdwYHuM';
     }
     this.url = this.sanitizer.bypassSecurityTrustResourceUrl(
       this.baseUrl + this.video.id
     );

   }

 }

I followed this guide to create it and it works for me, but the switch doesn't work for me.

Luca
  • 335
  • 3
  • 19

1 Answers1

1

From the looks of your code, it appears that you are implementing the OnInit interface but have not added the ngOnInit method. It would be better to add the ngOnInit method and then making the decision based on the input bindings in there rather then in constructor. This is because the OnInit lifecycle hook is called only after all the input bindings are resolved. Have a look here to know the difference : Difference between Constructor and ngOnInit . The reason why static data works is that its just like setting up a field with some string values that are already available, and this is obviously not the case with Input Bindings since they have not been resolved yet in the constructor.

So what you need to do is just move your code present in Constructor to ngOnInit method and let the sanitizer remain as it is in the constructor parameter. The dependency injector would ensure that the DOMSanitizer gets injected.And that should be it.

  • thank you so much! another thing, do you think there is a cleaner way to avoid the switch? it doesn't seem like a best practice to me, but I'm not sure, I'm new to angular. – Luca Mar 12 '21 at 08:07