使用iframe时,onLoad会发生多次 [英] onLoad happening multiple times with Iframe
问题描述
Angular 2存在一些问题,即制作一个具有iframe并根据输入设置源的组件.但是,在加载时,它两次按onLoad两次,一次是src=''
,另一次是实际的输入URL.
Having some issues with Angular 2, im making a component that has a iframe and sets the source from the input. However when it loads, it hits onLoad twice, one with src=''
and another with the actual input url.
我似乎无法弄清楚如何将iframe的网址插入视图中.
I cant seem to figure out how to hook the url up for the iframe when it gets put into the view.
export class ExternalComponent implements OnInit {
@Input()
url: string;
private src: any;
constructor(private sanitizer: DomSanitizer) {
}
ngOnInit()
{
this.src = this.sanitizer.bypassSecurityTrustResourceUrl(this.url)
}
onLoad() {
}
}
HTML:
<iframe [src]="src" frameBorder="0" (load)="onLoad()"></iframe>
复制: http://plnkr.co/edit/Dnpmv6X2IO3WGQAg0372?p=preview
谢谢
推荐答案
<打击>
您可以尝试属性绑定,如果值为null
You could try an attribute binding, which isn't added at all if the value is null
<iframe [attr.src]="src ? src = null" frameBorder="0" (load)="onLoad()"></iframe>
更新
如 https://stackoverflow.com/a/15880489/217408 中所述
在将<iframe>
添加到DOM之前将事件处理程序添加到元素时.这似乎就是Angular所做的.
As explained in https://stackoverflow.com/a/15880489/217408
when the event handler is added to the element before the <iframe>
is added to the DOM. This seems to be what Angular is doing.
在将元素添加到DOM后强制添加事件处理程序
Add event handler imperatively after the element was added to the DOM
url
为空时忽略事件
这篇关于使用iframe时,onLoad会发生多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!