source

Angular 2 애니메이션 - 부울 트리거?

nicesource 2023. 7. 18. 21:48
반응형

Angular 2 애니메이션 - 부울 트리거?

부울 속성에 바인딩된 전환을 트리거하려고 하지만 실행되지 않는 것 같습니다.

다음은 애니메이션 트리거의 축소 버전입니다.

trigger(
  'trueFalseAnimation', [
    transition('* => true', [
      style({backgroundColor: '#00f7ad'}),
      animate('2500ms', style({backgroundColor: '#fff'}))
    ]),
    transition('* => false', [
      style({backgroundColor: '#ff0000'}),
      animate('2500ms', style({backgroundColor: '#fff'}))
    ])
  ]
)

HTML:

<div [@trueFalseAnimation]="model.someProperty">Content here</div>

테스트 대상:

ngOnInit() {

    setTimeout(() => {
        this.model.someProperty = true;
        setTimeOut(() => {
            this.model.someProperty = false;
        }, 5000);    
    }, 1000)
}

트리거는 절대로 발생하지 않습니다.someProperty변화들.

빠른 테스트로 트리거를 문자열을 사용하도록 변경했는데 작동합니다.

trigger(
      'trueFalseAnimation', [
        transition('* => Success', [
          style({backgroundColor: '#00f7ad'}),
          animate('2500ms', style({backgroundColor: '#fff'}))
        ]),
        transition('* => Failed', [
          style({backgroundColor: '#ff0000'}),
          animate('2500ms', style({backgroundColor: '#fff'}))
        ])
      ]
    )

테스트 대상:

ngOnInit() {

    setTimeout(() => {
        this.model.someProperty = "Success";
        setTimeOut(() => {
            this.model.someProperty = "Failed";
        }, 5000);    
    }, 1000)
}

두 번째 예제는 잘 작동합니다.

제 질문은

  1. 부울이 트리거로 지원됩니까?
  2. #1에 동의하면 제가 무엇을 잘못하고 있습니까?
  1. 아닌 것 같습니다.이미 이에 대한 이슈(12337)가 제기된 것을 보았지만, 현재까지 업데이트된 사항은 없습니다.
  2. 또 다른 대안은 참과 거짓 대신 1과 0을 사용하는 것입니다.

여기플런커를 보세요.

trigger('isVisibleChanged', [
      state('true' , style({ opacity: 1, transform: 'scale(1.0)' })),
      state('false', style({ opacity: 0, transform: 'scale(0.0)'  })),
      transition('1 => 0', animate('300ms')),
      transition('0 => 1', animate('900ms'))
])

저도 같은 문제를 겪고 있습니다.부울이 트리거로 지원되는지 확실하지 않지만, 제가 찾은 해결 방법은 부울 값을 문자열로 반환하는 게터를 사용하여 문자열 속성을 정의하는 것이었습니다.이와 같은 것:

get somePropertyStr():string {
    return this.someProperty.toString();
}

그러면 당신은 당신의 애니메이션을 그것에 묶어야 합니다.somePropertyStr소유물.

다시 한 번 말하지만, 이것은 보기 흉한 해결 방법이며, 부울 값을 사용할 수 있는 것이 가장 좋습니다.

편집: 일부 다른 답변에서 암시하는 것처럼 동작이 변경되었습니다.관심이 있는 경우 관련 Angular 소스 코드가 여기에 있습니다.

const TRUE_BOOLEAN_VALUES = new Set<string>(['true', '1']);
const FALSE_BOOLEAN_VALUES = new Set<string>(['false', '0']);

function makeLambdaFromStates(lhs: string, rhs: string): TransitionMatcherFn {
  const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
  const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);

  return (fromState: any, toState: any): boolean => {
    let lhsMatch = lhs == ANY_STATE || lhs == fromState;
    let rhsMatch = rhs == ANY_STATE || rhs == toState;

    if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {
      lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);
    }
    if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {
      rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);
    }

    return lhsMatch && rhsMatch;
  };
}

직접 디버깅하는 경우가 아니라면 따라하기가 좀 까다롭지만 기본적으로 주의해야 할 중요한 점은fromState그리고.toState템플릿의 애니메이션에 설정한 값(변경 사항이 있는 경우)입니다. [@animation]="animationState"

그래서 당신은 그들이 불리언이 되도록 명시적으로 허용하는 것을 볼 수 있습니다.typeof fromState === 'boolean').

내가 잡힌 이유는 (그리고 나만의 예전 답으로 돌아가는 길을 찾았다) 앵글의AnimationEvent는 문자열로 정의합니다.

  /**
   * The name of the state from which the animation is triggered.
   */
  fromState: string;
  /**
   * The name of the state in which the animation completes.
   */
  toState: string;

따라서 애니메이션이 완료되면 상태가 부울로 설정됩니다(예: true/false그리고 아닙니다.'true'/'false'타이핑 문제가 발생할 것입니다.

의 실제 가치event.fromState아마도요.true그렇게

  • event.fromState == true컴파일러 오류를 제공합니다('string'과 'string'은 형식이 겹치지 않습니다).
  • event.fromState == 'true'값이 실제로이기 때문에 절대 사실이 아닐 것입니다.true)

따라서 다음 중 하나를 사용해야 합니다.

 if (<any>(event.toState) == true)

OR

 if ((event.toState as string | boolean) == true)

이전 답변:

국가는 하나의 끈으로 정의되기 때문에 우리는 그것을 고수할 필요가 있습니다.

당신의 코드에 기반한 가장 간단하지만 가장 까다로운 방법은 이것입니다.

<div [@trueFalseAnimation]="model.someProperty?.toString()">Content here</div>

하지만 이건 꽤 끔찍해요, 그래서 아마 이게 더 나을 거예요.

<div [@trueFalseAnimation]="model.someProperty ? 'active' : 'inactive'">Content here</div>
<div [@trueFalseAnimation]="model.someProperty ? 'visible' : 'hidden'">Content here</div>
<div [@trueFalseAnimation]="model.someProperty ? 'up' : 'down'">Content here</div>
<div [@trueFalseAnimation]="model.someProperty ? 'left' : 'right'">Content here</div>

여기서 가장 좋은 조언은 실제 의미와 일치하는 상태를 사용하는 것입니다.어쨌든 이 맥락에서 참과 거짓은 정말로 무엇을 의미합니까?

부울을 변환하기 위해 파이프를 만드는 것을 고려했지만, 유일한 이점은 상태 문자열과 일관성을 유지하는 것입니다.

언급URL : https://stackoverflow.com/questions/40340919/angular-2-animation-boolean-trigger

반응형