Dav*_*ave 6 javascript angularjs typescript angular-components angular
如何在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}`]);
}
}
Run Code Online (Sandbox Code Playgroud)
nextproduct() 绑定到模板中的单击事件.
这uidproduct是一个JSON对象,它有许多属性,我正在用它更新DOM{{uidproduct.classname}}
我在模板中使用这个:
<div id="selected-product" class="{{uidproduct.classname}}">
Run Code Online (Sandbox Code Playgroud)
当我单击<button (click)="nextproduct()">它将更改DOM中的类属性但我需要重新加载组件以使外部脚本生效.
Gün*_*uer 17
您可以使用*ngIf重新呈现模板的内容:
@Component({
selector: '...',
template: `
<ng-container *ngIf="!rerender">
template content here
</ng-container>`
})
export class MyComponent {
rerender = false;
constructor(private cdRef:ChangeDetectorRef){}
doRerender() {
this.rerender = true;
this.cdRef.detectChanges();
this.rerender = false;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么你需要重新加载该组件。如果您要绑定到 的各个字段uidproduct,则重新加载应该会刷新组件中显示的值。因此,重新加载组件只会增加开销。
如果这里没有提到一个很好的理由,为什么你认为你仍然需要这样做,那么你可以这样做:
问题是您需要等待第一个导航完成才能进行第二个导航。
在您的组件中,导入 NavigationEnd:
import { Router, NavigationEnd } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)
然后在你的构造函数中订阅它:
constructor(private thingService: ThisThingService, private router: Router) {
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (event.url === '/blank') {
this.router.navigate(['product']);
}
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,我等待NavigationEnd发生,然后检查是否路由到我的空白组件。如果它是空白组件的路径,我将导航回产品。如果您确实需要传递该 ID,只需将其存储在您的对象上并在此处添加即可。
不要路由到 中的产品页面nextproduct(),而是导航至blank。
this.router.navigate(['blank']);
Run Code Online (Sandbox Code Playgroud)
这应该可以很好地重新加载您的组件。
为了简单起见,我故意留下的问题是subscribe构造函数中的调用将在每次重新加载时执行。因此,作为读者的练习,将其从构造函数中取出并为其创建一个很好的服务,或者将其移动到应用程序组件的构造函数中,或者可能移动到路由模块中或任何对您有意义的地方。
| 归档时间: |
|
| 查看次数: |
32080 次 |
| 最近记录: |