gpt4 book ai didi

Angular 2 阅读更多指令

转载 作者:太空狗 更新时间:2023-10-29 17:00:17 25 4
gpt4 key购买 nike

我需要在 Angular2 中构建一个 readmore 指令。该指令将用于折叠和展开带有“阅读更多”和“关闭”链接的长文本 block 。不是基于字符数,而是基于指定的最大高度。

<div read-more [maxHeight]="250px" [innerHTML]="item.details">
</div>

任何人都可以指导在这种特定情况下获取/设置元素高度的最可靠方法。

任何有关如何实现此特定指令的指南也将受到高度赞赏。

我需要构建这样的东西 https://github.com/jedfoster/Readmore.js

解决方案:

在 Andzhik 的帮助下,我能够构建满足我要求的以下组件。

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>

如果有任何改进,请随时提出建议。

最佳答案

我制作了一个使用字符长度而不是 div 大小的版本。

import { Component, Input, ElementRef, OnChanges} from '@angular/core';

@Component({
selector: 'read-more',
template: `
<div [innerHTML]="currentText">
</div>
<a [class.hidden]="hideToggle" (click)="toggleView()">Read {{isCollapsed? 'more':'less'}}</a>
`
})

export class ReadMoreComponent implements OnChanges {
@Input() text: string;
@Input() maxLength: number = 100;
currentText: string;
hideToggle: boolean = true;

public isCollapsed: boolean = true;

constructor(private elementRef: ElementRef) {

}
toggleView() {
this.isCollapsed = !this.isCollapsed;
this.determineView();
}
determineView() {
if (!this.text || this.text.length <= this.maxLength) {
this.currentText = this.text;
this.isCollapsed = false;
this.hideToggle = true;
return;
}
this.hideToggle = false;
if (this.isCollapsed == true) {
this.currentText = this.text.substring(0, this.maxLength) + "...";
} else if(this.isCollapsed == false) {
this.currentText = this.text;
}

}
ngOnChanges() {
this.determineView();
}
}

用法:

<read-more [text]="text" [maxLength]="100"></read-more>

关于Angular 2 阅读更多指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com