我認爲這個問題是在空間id屬性。我可以在* ngFor中做到這一點。試試這個id="read-more{{i}}"
。 這裏是我的代碼:
<div *ngFor="let post of list;let i = index" [attr.data-index]="i">
<div class="postDescription">
<p #textContent1 id="read-more{{i}}">{{post.name}}</p>
<div class="readMore read-more-link">
<a readMore [readMore-length]="350"
[readMore-element]="textContent1">
<span class="more">Continue reading</span></a>
</div>
</div>
</div>
我已刪除了「少讀......」的功能,因爲它是不需要我的應用程序。
我複製了ngx-read-more庫的代碼並稍加修改。基本上做了一個自定義指令,而不是安裝包。
readmore.directive.ts
import { Directive, Input, ElementRef, AfterViewInit, OnChanges } from '@angular/core';
@Directive({
selector: '[readMore]'
})
export class ReadMoreDirective implements AfterViewInit, OnChanges {
@Input('readMore-length') private maxLength: number;
@Input('readMore-element') private elementChange: HTMLElement;
private currentText: string;
private hideToggle: boolean = true;
private text: string;
private isCollapsed: boolean = true;
constructor(private el: ElementRef) {}
/**
* @inheritDoc
*/
public ngAfterViewInit() {
this.text = this.elementChange.innerHTML;
this.toggleView();
if (!this.hideToggle) {
this.el.nativeElement.classList.remove('hidden');
} else {
this.el.nativeElement.classList.add('hidden');
}
this.el.nativeElement.addEventListener('click', (event: MouseEvent) => {
event.preventDefault();
this.toggleView();
});
}
/**
* @inheritDoc
*/
public ngOnChanges() {
if (this.text) {
this.toggleView();
}
}
/**
* Toogle view - full text or not
*/
private toggleView(): void {
this.determineView();
this.isCollapsed = !this.isCollapsed;
if (this.isCollapsed) {
this.el.nativeElement.querySelector('.more').style.display = "none";
//this.el.nativeElement.querySelector('.less').style.display = "inherit";
} else {
this.el.nativeElement.querySelector('.more').style.display = "inherit";
//this.el.nativeElement.querySelector('.less').style.display = "none";
}
}
/**
* Determine view
*/
private determineView(): void {
const _elementChange = document.getElementById(this.elementChange.id);
if (this.text.length <= this.maxLength) {
this.currentText = this.text;
_elementChange.innerHTML = this.currentText;
this.isCollapsed = false;
this.hideToggle = true;
return;
}
this.hideToggle = false;
if (this.isCollapsed === true) {
this.currentText = this.text.substring(0, this.maxLength) + '...';
_elementChange.innerHTML = this.currentText;
} else if (this.isCollapsed === false) {
this.currentText = this.text;
_elementChange.innerHTML = this.currentText;
}
}
}
你有沒有找到解決辦法還沒有這個問題?如果你有問題,你可以請回答問題嗎? – shahakshay94
沒有我仍然無法解決 –