0

In Angular 2, how do I animate one element so that it's size and position will match that of another target element? The target element's size and position is not fixed, but can vary at runtime. Attached is a complete example using jQuery. As a bonus, I'm wondering if the animation can be done without using an ElementRef?

Codepen

See the Pen Animate element on top of another by Matthew Banz (@battmanz) on CodePen.

HTML

<section>
  <button id="animateBlue">Animate Blue</button>
  <button id="randomizeOrange">Randomize Orange</button>
</section>

<section>
  <div class="ball" id="ball1"></div>
  <div class="ball" id="ball2"></div>
</section>

CSS

body {
  margin: 0;
  padding: 0;
}

section:first-of-type {
  padding: 10px;
  text-align: center;
  background-color: #ccc;
}

.ball {
  border-radius: 50%;
  position: absolute;
}

#ball1 {
  background-color: blue;
  z-index: 5;
}

#ball2 {
  background-color: orange;
}

JS

const ball1 = $('#ball1');
const ball2 = $('#ball2');

function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomlyAssignOrangePositionSize() {
  const radius = getRandomIntInclusive(10, 200);
  const top = getRandomIntInclusive(50, 300);
  const left = getRandomIntInclusive(10, 900);

  ball2.css({
    width: radius,
    height: radius,
    top: top,
    left: left
  });
}

ball1.css({
  width: 50,
  height: 50,
  top: 100,
  left: 50
});

randomlyAssignOrangePositionSize();

$('#randomizeOrange').click(randomlyAssignOrangePositionSize);

$('#animateBlue').click(function() {
  ball1.animate({
    width: ball2.css('width'),
    height: ball2.css('height'),
    top: ball2.css('top'),
    left: ball2.css('left')
  });
});
4

1 回答 1

0

我会继续回答我自己的问题。事实证明,从 RC5 开始,这在 Angular 2 中目前是不可能的。为了执行动画,我需要在运行时计算样式。这是目前在 Github 上的一个开放功能请求:

功能请求:允许 style()、keyframes() 等中的绑定表达式...

特别是,查看@dpix 的评论和@matsko 的答案。

于 2016-08-23T21:17:34.540 回答