【问题标题】:Add newly created element to Angular template element将新创建的元素添加到 Angular 模板元素
【发布时间】:2018-08-24 19:52:24
【问题描述】:

所以我想在我的 Angular 模板中的现有元素中添加一个新的视频元素。我尝试的是使用@ViewChild 获取模板的元素,并使用.appendChild() 添加我创建的其他元素。不幸的是,Viewchild 给了我一个 elementRef,因此我不能简单地使用 .appendChild()。有人知道替代方案吗?

**这里是组件:我抓住了 viewZone 元素,并希望我可以简单地执行类似 .appendChild() 的操作,但令我惊讶的是,它是一个 elementRef,所以我现在不知道该做什么。 **

import {Component, OnInit, ViewChild} from "@angular/core";
import {ActivatedRoute} from "@angular/router";
import {MovieService} from "../movie/movie.service";

@Component({
    selector: 'app-trailers',
    templateUrl: './trailers.component.html',
    styleUrls: ['./trailers.component.css']
})

export class TrailersComponent implements OnInit{

    trailerIdArray;
    @ViewChild('trailerZone') trailerZone;

    constructor(private route: ActivatedRoute){

    }

    ngOnInit(){
        this.route.queryParams.subscribe( params => {
            let id = params.id;
            this.createDynamicEmbeddedYoutubeTrailer(id);
        });
    }

    createDynamicEmbeddedYoutubeTrailer(id){
        let trailerElem = document.createElement("iframe");
        trailerElem.setAttribute("width", "560");
        trailerElem.setAttribute("height", "315");
        trailerElem.setAttribute("src", "https://www.youtube.com/embed/" + id);
        trailerElem.setAttribute("frameBorder", "0");
        trailerElem.setAttribute("allow", "autoplay: encrypted-media");
        trailerElem.setAttribute("allowfullscreen", "");

        console.log(this.trailerZone);
        console.log(trailerElem);
    }
}

模板

<div class="col col-md-8 col-md-offset-2">
        <div #trailerZone class="trailerZone">
            <button class="btn btn-primary previousButton">Previous</button>
            <button class=" btn btn-primary nextButton">Next</button>
        </div>
</div>

两个元素的两个console.logs

<iframe width="560" height="315" src="https://www.youtube.com/embed/XFYWazblaUA" frameborder="0" allow="autoplay: encrypted-media" allowfullscreen=""></iframe>



ElementRef {nativeElement: div.trailerZone}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    这里有一个更角度的方法:

    创建一组 youtube 视频 ID,例如:

    videoIds: string[] = [
      'KhzGSHNhnbI',
      'hAaoPOx_oIw',
      'WjcL09xgo3o'
    ];
    
    // add video function
    createDynamicEmbeddedYoutubeTrailer(id) {
      this.videoIds.push(id);
    }
    

    HTML:

    <iframe width="100%" 
            height="131"  
            *ngFor="let id of videoIds"
            [src]="('https://www.youtube.com/embed/' + id) | safe"
            frameborder="0" 
            allow="autoplay: encrypted-media" 
            allowfullscreen=""></iframe>
    

    safe 这里的管道告诉 Angular 给定的src 值可以安全使用。 也添加这个管道(复制自similar answer):

    @Pipe({ name: 'safe' })
    export class SafePipe implements PipeTransform {
      constructor(private sanitizer: DomSanitizer) {}
      transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
      }
    }
    

    带有输入文本字段和“添加视频”按钮的 STACKBLITZ:https://stackblitz.com/edit/angular-dacotr?file=app%2Fapp.component.ts

    【讨论】:

    • 非常有趣!
    • 我如何在模板中只显示其中一个?
    • 我也仍然得到这个错误:Error parsing header X-XSS-Protection: 1;模式=块;报告=google.com/appserve/security-bugs/log/youtube:在字符位置 22 的安全页面的不安全报告 URL。将应用默认保护。
    • 我更新了我的 stackblitz,只显示一部没有ngFor 的电影,导航是通过按钮完成的。关于这个错误,它似乎是 Chrom 的错误,更多细节请参阅stackoverflow.com/questions/48714879/…
    【解决方案2】:

    可以使用this.trailerZone.nativeElement获取原生元素,可以对其进行DOM操作,比如appendChild

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 2011-09-05
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      相关资源
      最近更新 更多