Angular 2在*ngFor中只对一个元素执行动画

4
我在*ngFor中使用动画。当我点击并执行动画时,它会循环地对所有元素进行动画,但我只想对一个元素进行动画。我该如何做到这一点?

http://joxi.ru/82QYVWGSjBRGM2

   @Component({
    selector: 'app-popular-sensor',
    templateUrl: './popular-sensor.component.html',
    styleUrls: ['./popular-sensor.component.css'],
    animations: [
        trigger('focusPanel', [
            state('in', style({
                height: '20px'
            })),
            state('out', style({
                height: '*',
            })),
            transition('in => out', animate('400ms ease-in-out'))
        ])
    ]
})

export class PopularSensorComponent implements OnInit {

    goods;
    state = 'in';

    constructor(private goodsService: GoodsService) {
        goodsService.getGoods()
            .subscribe(goods => {
                this.goods = goods;
                console.log(this.goods);
            });
    }

    toggleChar() {
        this.state = this.state === 'in' ? 'out' : '';
    }

    ngOnInit() {

    }

}

HTML:

  <div *ngFor="let g of goods"
         class="col-sm-4 col-xs-12">
        <div class="sensor-block">

            <div class="char_block"
                 [@focusPanel]="state">
                <small *ngFor="let c of g.charact">{{c.name}}</small>
            </div>

            <div class="characteristic"
                 (click)="toggleChar()">Все характеристики смарт стола
            </div>
        </div>
    </div>

你可以尝试使用query吗?更多信息请参考这里:https://www.yearofmoo.com/2017/06/new-wave-of-animation-features.html#using-query-and-stagger - Aravind S
谢谢,它起作用了!但我认为我可以不为每个元素创建数组来做到这一点,无论如何,这是一个很好的例子。 - Стас Рябцев
1个回答

3
“关键”不是使用全局变量,而是属于对象“g”的变量。
<!--g.state-->
<div class="char_block" [@focusPanel]="g.state">
  <small *ngFor="let c of g.charact">{{ c.name }}</small>
</div>

<!--change g.state-->
<div class="characteristic" (click)="g.state=='in' ? 'out':'in'">
  Все характеристики смарт стола
</div>

我无法看到所有图片是如何工作的,但这个很好运行 https://ng-run.com/edit/M5QOQGw0wruwXi0DiorT 谢谢! - Стас Рябцев
简要解释一下:你有一个对象数组,在已经存在的对象中,你可以简单地添加一个变量 myobject.newproperty=value(如果在你的 .html 中写入 {{goods |json }},你就可以看到它)。如果这个对象没有属性“newpropery”,myobject.newproperty 将把它添加到对象中,如果对象有该属性,则更改属性的值。我希望不要调用函数,只使用三元运算符。当 g.state 为 'in' 时,g.state=='in' 才为真(如果未定义,则不符合条件)。 - Eliseo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接