代码之家  ›  专栏  ›  技术社区  ›  Stefan Falk

如何更新子模型而不重置整个视图?

  •  2
  • Stefan Falk  · 技术社区  · 6 年前

    我对angular还是比较陌生,只是找不到以下问题的例子:

    items item 从父级传递 ItemsComponent 对一个孩子 ItemComponent 组件。经典的例子。

    项目 只要有变化。所以我们每5秒钟做一次讨厌的民意测验(欢迎提出更好的解决方案的建议)。这将更新 并摧毁每一个 项目组件 子对象以创建新的子对象。

    @Component({
      selector: 'app-items',
      templateUrl: './items.component.html',
      styleUrls: ['./items.component.css'],
      template:`
        <div *ngFor="let item of items">
          <app-item [item]="item"></app-item>
        <div>
      `
    })
    export class ItemsComponent implements OnInit {
    
      private polling;
    
      public items: Array<ItemModel>;
    
      constructor(private itemsService: ItemsService) {}
    
      ngOnInit() {
        this.polling = interval(5000).pipe(
           startWith(0),
           map(() => {
             this.itemsService.getItems().subscribe(
               (items) => {this.items = items;});
            })
          ).subscribe((data) => this.processData(data));
        }
      }
    
      ngOnDestroy() {
        this.polling.unsubscribe();
      }
    }
    

    现在有几个问题:

    • 猛地咬住

    所有这些都必须在父组件中记住和处理。

    那么,这是一场“角度”战争,还是我必须自己在父组件中实现更新逻辑?

    *ngFor @ViewChildren 但我无法实现我在这里所追求的目标。

    那么我们如何用angular更新列表视图中的项呢?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Stefan Falk    6 年前

    你可以用 trackBy 仅限重新提交更新的项目。

    所有的角度都是关于可观察的尝试使用 asyncPipe

    @Component({
      selector: 'app-items',
      templateUrl: './items.component.html',
      styleUrls: ['./items.component.css'],
      template: `
        <ng-container *ngIf="items$|async as items">
          <div *ngFor="let item of items; trackBy:item?.uniqueProp">
            <app-item [item]="item"></app-item>
          <div>
        </ng-container>
      `
    })
    export class ItemsComponent implements OnInit {
      public items$: Observable<Array<ItemModel>>;
    
      constructor(private itemsService: ItemsService) {}
    
      ngOnInit() {
        this.items$ = interval(5000).pipe(
          startWith(0),
          map(() => this.itemsService.getItems())
        );
      }
    }