如何告诉角度不更新视图 [英] How to tell angular not to update view

查看:66
本文介绍了如何告诉角度不更新视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

<ng-container *ngFor="let item of items;">
    // other stuff
</ng-container>

我的 items 更改角度后,就会立即重置< ng-container> 内的视图.内部的区域具有内部形成的手风琴.因此,当更新任何表格时,手风琴部分都将关闭,这不是理想的功能.如何防止这种情况发生?

As soon as my items changes angular resets the view inside <ng-container>. The region inside has accordions which has forms inside. So when any of the forms are updated the accordion sections get closed and this is not a desirable feature. How can I prevent this from happening?

推荐答案

您需要避免循环访问可以更改的变量.我不知道您的代码,但总的来说,您总是可以做到的

You need avoid loop over a variable that can change. I don't know about your code, but in general you always can do

<ng-container *ngFor="let foo of count;let i=index">
    // other stuff but you use
    items[i]
</ng-container>

您有变量的地方

count:any[];

请记住,当您更改项目的长度时,您需要写出

And remember that, when you change the length of item you need write

this.count = new Array(items.length); 

如果您不必担心何时更改项目长度,则可以使用字符串的重复和拆分功能即时"创建数组:

If you don't worry about when you change the items length you can create the array "on-fly" using repeat and split functions of string:

<ng-container *ngFor="let foo of ' '.repeat(items.length).split('');let i=index">
    // other stuff but you use
    items[i]
</ng-container>

其他方法是创建指令重复

Other way is create a directive repeat

@Directive({
  selector: '[repeat]'
})
export class RepeatDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }

  @Input() set repeat(times: number) {
    let count=this.viewContainer.length;
    for (let i=this.viewContainer.length;i>times;i--)
      this.viewContainer.remove(i-1);

    for (let i = count ; i < times ; i++) 
      this.viewContainer.createEmbeddedView(this.templateRef,
      {
        $implicit:i
      });

  }
}

并使用

<ng-container *repeat="items.length;let i">
..use item[i]...
</ng-container>

这篇关于如何告诉角度不更新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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