IT虾米网

javascript之Angular 5 和转换仅在 'new' 项中

powertoolsteam 2024年06月20日 程序员 87 0

我的组件的模板呈现一个列表:

<div class="row"> 
  <div *ngFor="let m of activeModules" [@enterAnimation]> 
    {{ m.name }} 
  </div> 
</div> 

组件为其设置动画

@Component({ 
  selector: 'app-client-detail', 
  templateUrl: './client-detail.component.html', 
  styleUrls: ['./client-detail.component.scss'], 
  animations: [ 
 
    trigger( 
      'enterAnimation', [ 
        transition(':enter', [ 
          style({ opacity: 0 }), 
          animate('1000ms', style({ opacity: 1})) 
        ]), 
        transition(':leave', [ 
          style({ opacity: 1 }), 
          animate('1000ms', style({ opacity: 0})) 
        ]) 
      ] 
    ) 
  ] 
}) 
export class ClientDetailComponent implements OnInit { 
   activeModules = [{ name: 'modulo 1'}, { name: 'modulo 2'}]; 
} 

这工作正常,“div”具有不透明度的过渡。 如果我做这样的事情:

ngOnInit() { 
  Observable.timer(2000).subscribe(() => { 
    this.activeModules =  [{ name: 'modulo 1'}, { name: 'modulo 3'}, { name: 'modulo 2'}]; 
} 

activeModules 的数组已更新,模板再次呈现带有转换的列表。我的问题是,我只需要数组中的"new"项(在本例中为中间的项)即可进行转换。可能吗?

请您参考如下方法:

当然,您只需要推送您的项目,而不需要再次创建数组。

让我们为此创建一个函数:

pushAt(arr, index, item) { 
  arr.splice(index, 0, item);  
} 

现在你可以

ngOnInit() { 
  Observable.timer(2000).subscribe(() => this.pushAt(this.activeModules, 1, { name: 'Modulo 2' })); 
} 

编辑也许您可以尝试使用自定义 trackby 函数:

customTrackBy(index, item) { return index; } 

在 HTML 中

<div *ngFor="let m of activeModules; trackBy: customTrackBy;" [@enterAnimation]> 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!