【发布时间】:2017-03-19 07:56:33
【问题描述】:
如何在 Angular 2 中重新加载相同的组件?
下面是我的代码:
import { Component, OnInit, ElementRef, Renderer } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { productModel } from '../_models/index';
import { categoryListService } from '../_services/index';
@Component({
selector: 'app-product',
templateUrl: 'product.component.html',
styleUrls: ['product.component.css']
})
export class productComponent implements OnInit {
uidproduct: productModel;
param: number;
constructor(
private elementRef: ElementRef,
private route: ActivatedRoute,
private router: Router,
private categoryListService: categoryListService) { }
ngOnInit() {
this.route.params.subscribe(product => {
console.log('logging sub product obj', product);
});
this.uidproduct = JSON.parse(sessionStorage.getItem('product'));
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://this/external/script/needs/to/be/loaded/each/time.js";
this.elementRef.nativeElement.appendChild(s);
}
nextproduct(){
let i = this.uidproduct.order;
this.categoryListService.findNextproduct(this.uidproduct);
this.param = ++i;
this.router.navigate([`/product/${this.param}`]);
}
}
nextproduct() 绑定到模板中的点击事件。
uidproduct 是一个 JSON 对象,它具有许多属性,我正在使用 {{uidproduct.classname}} 更新 DOM
我在这样的模板中使用它:
<div id="selected-product" class="{{uidproduct.classname}}">
当我单击<button (click)="nextproduct()"> 时,它将更改 DOM 中的类属性,但我需要重新加载组件才能使外部脚本生效。
【问题讨论】:
-
我不认为组件重新加载选项会很好,我需要重新加载组件以使外部脚本生效。?
-
外部脚本针对特定的 DOM 元素类属性并将特定产品呈现给 DOM。干杯!
-
什么外部脚本?
-
@Dave 你不能从模板加载外部脚本(这将是安全威胁),我建议你通过this question
-
@PankajParkar 我现在已经从模板中删除了外部脚本,但是关于如何重新加载组件的任何更新都会很棒!
标签: javascript angular typescript angular-components