gpt4 book ai didi

Angular 2 - 显示一个元素并隐藏其他元素,

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

问题:

我有一个包含 4 个元素的 Accordion ,每个元素都隐藏了要显示的内容,当我单击第一个元素时,它没有显示第一个元素的内容,而是显示了其他 3 个元素。

预期行为:

我想点击第一个元素,然后显示属于该元素的内容并继续隐藏其他内容。

代码:

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-sabias-que',
templateUrl: './sabias-que.component.html',
styleUrls: ['./sabias-que.component.scss']
})
export class SabiasQueComponent implements OnInit {

private _isOpen : boolean = false;
private tips : Array<any> = [
{
heading: 'Title 1',
content: 'Content to be displayed'
},
{
heading: 'Title 1',
content: 'Content to be displayed'
},
{
heading: 'Title 1',
content: 'Content to be displayed'
},
{
heading: 'Title 1',
content: 'Content to be displayed'
}
]

closeOthers(openGroup): void {
this.tips.forEach((tip) => {
if (tip !== openGroup) {
tip.isOpen = false;
}
});
}

set isOpen(value: boolean) {
debugger;
this._isOpen = value;
if (value) {
this.closeOthers(this);
}
}

get isOpen() {
return this._isOpen;
}



constructor() { }

ngOnInit() {
}

showContent(): void {
this.isOpen = !this.isOpen;
}

}

HTML:

<ul class="tips-list">
<li *ngFor="let tip of tips">
<h3 class="tips-list__title"
[ngClass]="{'tips-list__title--active' : isOpen}" (click)="showContent()">
{{ tip.heading }}
</h3>
<p class="tips-list__answer" [hidden]="!isOpen">
{{ tip.content }}
</p>
</li>
</ul>

如果有人提供并回答,我将不胜感激代码或概念解释,我知道如何使用 jQuery 或 vanilla JS 执行此操作,但由于它是 OOP,我不明白 'this' 的用法完全没有。

最佳答案

在所有这些方法中,this 属于组件(SabiasQueComponent 的实例),而不属于每个tip

有几种可能的解决方案,下面显示了一种建议。

Check demo plunker here

模板:

  <ul class="tips-list">
<li *ngFor="let tip of tips">
<h3 class="tips-list__title"
[ngClass]="{'tips-list__title--active' : tip.isOpen}" (click)="showContent(tip)">
{{ tip.heading }}
</h3>
<p class="tips-list__answer" [hidden]="!tip.isOpen">
{{ tip.content }}
</p>
</li>
</ul>

注意三个变化:"{'tips-list__title--active' : isOpen}""{'tips-list__title--active' : tip.isOpen}"(click)="showContent()"(click)="showContent(tip)"[hidden]="!isOpen">[hidden]="!tip.isOpen">。基本上,我们现在从每个提示中获取属性,而不是从组件中获取。

组件:

export class SabiasQueComponent implements OnInit {

private _isOpen : boolean = false;
private tips : Array<any> = [
// all the same
]

closeAllTips(): void {
this.tips.forEach((tip) => {
tip.isOpen = false;
});
}

showContent(tip) {
if (!tip.isOpen) {
this.closeAllTips();
}
tip.isOpen = !tip.isOpen;
}

constructor() { }

ngOnInit() {
}

}

在组件代码中,showContent() 已更改为现在接收将显示其内容的提示get isOpen()set isOpen() 已被删除,因为这将成为每个 tip 的属性。并且 closeOthers(openGroup) 被移除以支持新的 closeAllTips()

关于Angular 2 - 显示一个元素并隐藏其他元素,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424850/

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