>on click an English button it shows its corresponding div at the same time if I clicked on another button then it shows its div but the previous one not closed. I want that on click English it shows the div and on again click it close.
>Note that makes it dynamically because I don't know how many lang are there.
>make sure you don't make it for static data.
<div *ngFor="let lang of langList;let index = index" >
<div class="engbutton">
<button class="englishButton" (click)="onclickEnglishDiv(lang,index)">{{ lang }}</button>
<div *ngIf="visibleIndex === index" class="knowEnglish">
<div>
<div *ngFor="let data of filteredLangList" class="engDivObj">{{data.name}}</div>
</div>
</div>
</div>
</div>
在我的TS中
onclickEnglishDiv(clickLang,index){
if (this.visibleIndex !== index) {
this.visibleIndex = index;
}
}
I want that on click first button it opens its div,
on click second button it opens its div .but, doesn't close the first one. The first one is closed when the first button only clicked.
- make it dynamically like when new data come it works with the flow.
这是我的示例https://stackblitz.com/edit/angular-showhide-088?file=src%2Fapp%2Fsho-hide%2Fsho-hide.component.html
在这里可以找到它的jquery版本:https://www.bootply.com/90JfjI2Q7n 我需要在angular 7中使用动态类型而不是核心的上述功能 像为每个div定义布尔值一样的类型。
答案 0 :(得分:1)
一种解决方案可能是不存储可见索引,而是存储可见索引,例如:
<div class="box">
<div class="container">
<div *ngFor="let lang of langList;let index = index" >
<div class="engbutton">
<button class="englishButton" (click)="onclickEnglishDiv(lang, index)">{{ lang }}</button>
<div *ngIf="visibleIndices.has(index)" class="knowEnglish">
<div>
<div *ngFor="let data of studentList | filterLanguages:lang" class="engDivObj">{{data.name}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
...
export class ShoHideComponent implements OnInit {
visibleIndices = new Set<number>();
...
onclickEnglishDiv(clickLang, index): void {
if (!this.visibleIndices.delete(index)) {
this.visibleIndices.add(index);
}
}
}
您可能还会注意到,我将语言过滤器逻辑移到了filterLanguages
pipe中,因为每个元素应具有自己的过滤后语言副本,否则所有元素都将显示相同的项目。 stackblitz link
另一种解决方案可能是为按钮创建一个单独的组件,例如:
<!-- sho-hide.component.html -->
<div class="box">
<div class="container">
<div *ngFor="let lang of langList;let index = index" >
<app-lng-button [lang]="lang" [languages]="studentList | filterLanguages:lang"></app-lng-button>
</div>
</div>
</div>
// lng-button.component.ts
@Component({
selector: 'app-lng-button',
templateUrl: './lng-button.component.html'
})
export class LngButtonComponent {
@Input()
lang!: string;
@Input()
languages: string[] = []
open = false;
}
<!-- lng-button.component.html -->
<div class="engbutton">
<button class="englishButton" (click)="open = !open">{{ lang }}</button>
<div *ngIf="open" class="knowEnglish">
<div>
<div *ngFor="let data of languages" class="engDivObj">{{data.name}}</div>
</div>
</div>
</div>