Trước tiên, hãy tạo tệp nơi bạn sẽ xác định hoạt ảnh của mình và xuất chúng. Chỉ để làm rõ hơn trong app.component.ts
Trong ví dụ sau, tôi đã sử dụng chiều cao tối đa của div đi từ 0px (khi được ẩn), đến 500px, nhưng bạn sẽ thay đổi điều đó theo với những gì bạn cần.
Hoạt ảnh này sử dụng trạng thái (vào và ra), sẽ chuyển đổi khi chúng ta nhấp vào nút, nút này sẽ chạy hoạt ảnh.
animations.ts
import { trigger, state, style, transition,
animate, group, query, stagger, keyframes
} from '@angular/animations';
export const SlideInOutAnimation = [
trigger('slideInOut', [
state('in', style({
'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
})),
state('out', style({
'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
})),
transition('in => out', [group([
animate('400ms ease-in-out', style({
'opacity': '0'
})),
animate('600ms ease-in-out', style({
'max-height': '0px'
})),
animate('700ms ease-in-out', style({
'visibility': 'hidden'
}))
]
)]),
transition('out => in', [group([
animate('1ms ease-in-out', style({
'visibility': 'visible'
})),
animate('600ms ease-in-out', style({
'max-height': '500px'
})),
animate('800ms ease-in-out', style({
'opacity': '1'
}))
]
)])
]),
]
Sau đó, trong app.component của bạn, chúng tôi nhập khẩu các hình ảnh động và tạo ra các phương pháp đó sẽ chuyển đổi trạng thái hoạt hình.
app.component.ts
import { SlideInOutAnimation } from './animations';
@Component({
...
animations: [SlideInOutAnimation]
})
export class AppComponent {
animationState = 'in';
...
toggleShowDiv(divName: string) {
if (divName === 'divA') {
console.log(this.animationState);
this.animationState = this.animationState === 'out' ? 'in' : 'out';
console.log(this.animationState);
}
}
}
Và đây là cách bạn app.component.html sẽ trông như thế:
<div class="wrapper">
<button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
<div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
THIS DIV IS ANIMATED</div>
<div class="content">THIS IS CONTENT DIV</div>
</div>
slideInOut đề cập đến việc kích hoạt hoạt hình được xác định trong animations.ts
Đây là StackBlitz ví dụ tôi đã tạo: https://stackblitz.com/edit/angular-muvaqu
Side lưu ý: Nếu một lỗi bao giờ xảy ra và yêu cầu bạn thêm BrowserAnimationsModule, chỉ cần nhập nó trong app.module.ts của bạn:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [ ..., BrowserAnimationsModule ],
...
})
Cảm ơn bạn rất nhiều:) –
Cảm ơn bạn vì điều này. Nó rất hữu ích cho dự án của tôi –