如何重新加载当前的Angular 2组件 [英] How to reload the current Angular 2 Component

查看:1219
本文介绍了如何重新加载当前的Angular 2组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular 2中重新加载相同的组件?

How can I reload the same component again in 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()绑定到模板中的click事件。

nextproduct() is bound to a click event in the template.

uidproduct 是一个JSON对象,有许多属性,我用 {{uidproduct.classname}}更新DOM

The uidproduct is a JSON object that has a number of properties and i'm updating the DOM with {{uidproduct.classname}}

我'我在模板中使用这个:

I'm using this in the template like this:

<div id="selected-product" class="{{uidproduct.classname}}">

点击<按钮(点击)=nextproduct() > 它将更改DOM中的类属性,但我需要重新加载组件以使外部脚本生效。

When I click the <button (click)="nextproduct()"> it will change the class property in the DOM but I need to reload the component for the external script to have effect.

推荐答案

您可以使用 * ngIf 重新呈现模板的内容:

You can use *ngIf to re-render the content of a template:

@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;
  }
}

这篇关于如何重新加载当前的Angular 2组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆