import { Component,Input,ElementRef,AfterViewInit } from '@angular/core'; @Component({ selector: 'read-more',template: ` <div [innerHTML]="text" [class.collapsed]="isCollapsed" [style.height]="isCollapsed ? maxHeight+'px' : 'auto'"> </div> <a *ngIf="isCollapsable" (click)="isCollapsed =! isCollapsed">Read {{isCollapsed? 'more':'less'}}</a> `,styles: [` div.collapsed { overflow: hidden; } `] }) export class ReadMoreComponent implements AfterViewInit { //the text that need to be put in the container @Input() text: string; //maximum height of the container @Input() maxHeight: number = 100; //set these to false to get the height of the expended container public isCollapsed: boolean = false; public isCollapsable: boolean = false; constructor(private elementRef: ElementRef) { } ngAfterViewInit() { let currentHeight = this.elementRef.nativeElement.getElementsByTagName('div')[0].offsetHeight; //collapsable only if the contents make container exceed the max height if (currentHeight > this.maxHeight) { this.isCollapsed = true; this.isCollapsable = true; } } }
使用如下:
<read-more [text]="details" [maxHeight]="250"></read-more>
该组件运作良好.现在我需要向组件添加一些向上/向下滑动动画,以便在单击“阅读更多”链接时向下滑动内容,单击“阅读更少”时,内容将向上滑动到指定的最大高度.
任何人都可以指导如何实现这一目标?
Automatic property calculation
Animation with automated height calculation
Sometimes you don’t know the value of a dimensional style property
until runtime. For example,elements often have widths and heights
that depend on their content and the screen size. These properties are
often tricky to animate with CSS.In these cases,you can use a special * property value so that the
value of the property is computed at runtime and then plugged into the
animation.In this example,the leave animation takes whatever height the element
has before it leaves and animates from that height to zero :06000
来自Angular官方文档:https://angular.io/guide/animations#automatic-property-calculation