깜놀하는 해므찌로

Angular Youtube 앵귤러 유튜브 재생 예시 / getter 본문

IT

Angular Youtube 앵귤러 유튜브 재생 예시 / getter

agnusdei1207 2023. 6. 1. 17:31
반응형
SMALL
yarn add @angular/youtube-player

0. 패키지 설치 cli

 

<div #videoContainer class="w-full overflow-hidden rounded-md">
      <youtube-player
        [videoId]="extractVideoId"
        suggestedQuality="highres"
        [width]="youtubeWidth"
        [height]="youtubeHeight"
        [playerVars]="youtubePlayerOptions"
      >
      </youtube-player>
    </div>

1. div 태그로 한 번 더 감싸서 크기 조절을 합니다.

2. 앵귤러 제공 네이티브 태그를 사용합니다. youtube-player

3. playerVars = "유튜브 옵션을 설정합니다."

4. [videoId]="getter 메소드"

 

 

import { YouTubePlayerModule } from '@angular/youtube-player';


// 사이즈 조절을 위해 viewVhild 선언
@ViewChild('videoContainer')videoContainer!: ElementRef<HTMLDivElement>;

@Input() post!: DTO; 통신 DTO

youtubeWidth: number = 0;
youtubeHeight: number = 0;

youtubePlayerOptions: YT.PlayerVars = {
    autoplay: 1, // 자동재생
    controls: 0, // 컨트롤러 가리기
    modestbranding: 1, // youtube 마크 
    rel: 0, // 관련 영상 추천 
};


ngAfterViewInit(): void { // view 가 그려진 후 실행
    setTimeout(() => {
      this.onResize();
    }, 100);
    // 윈도우 사이즈 변경이 발생한다면? onResize 함수 실행
    window.onresize = () => this.onResize();
  }


// getter 비디오 ID 추출 메소드
get extractVideoId(): string {
    let videoId = '';
    if (this.post.video.includes('youtube.com/shorts')) {
      const parts = this.post.video.split('/');
      const lastIndex = parts.length - 1;
      videoId = parts[lastIndex].split('?')[0];
    } else {
      const regExp =
        /^(?:https?:\/\/(?:www\.)?youtube\.com\/(?:watch\?.*v=|embed\/)|https?:\/\/youtu.be\/)([\w-]+)(?:\?.*)?$/i;
      const match = this.post.video.match(regExp);
      if (match) {
        videoId = match[1] || '';
      }
    }
    return videoId;
  }
  
// reponsive 를 위한 사이즈 조절 메소드
onResize() {
    const { clientWidth } = this.videoContainer.nativeElement;

    this.youtubeWidth = clientWidth;
    // 16:9 비율
    this.youtubeHeight = clientWidth * 0.5625;
}

3. 자세한 설명은 주석에 적었습니다.

반응형
LIST