【发布时间】: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