【问题标题】:Angular 2. Change class ONLY of focused elementAngular 2. 仅更改焦点元素的类
【发布时间】:2016-11-20 19:52:50
【问题描述】:

我的按钮和div 元素很少。 divs 被隐藏。我想在单击特定按钮时显示特定的div

例如:您单击第一个按钮 - 只有第一个 div 出现(通过更改他的类出现)。

代码:app.component.html

<button class="BUTTON" (click)="isHidden = !isHidden">
</button>
<div class="ELEMENTTOSHOW" [ngClass]="{ 'subMenuShow':isHidden }">first
</div>

<button class="BUTTON" (click)="isHidden = !isHidden">
</button>
<div class="ELEMENTTOSHOW" [ngClass]="{ 'subMenuShow':isHidden }">second
</div>

app.component.ts

export class AppComponent {
  isHidden = false;
}

这个解决方案是错误的,因为当我点击例如首先 BUTTON 然后两个 div ELEMENTTOSHOW 出现。它不应该那样工作,它应该只在特定的 div 上工作。

任何帮助表示赞赏。

编辑: 这是我在 plunker 上的代码预览:

https://plnkr.co/edit/BQKanrtuoADClGLVSdBC?p=preview

它不是我的整个应用程序,只有提到的、非常简化的部分。

我已经添加了AngularJS标签,因为你可以给我一个与angular1相关的解决方案,我将它重写为angular2。

【问题讨论】:

  • 您能否向 Plunker 提供您应用程序的当前状态?在上面显示的代码 sn-ps 中没有任何实际的按钮,只有具有“按钮”类的 元素。

标签: javascript angularjs angular


【解决方案1】:

我会这样重组它:

HTML

<button class="BUTTON" (click)="isHiddenfirst = !isHiddenfirst">
</button>
<div *ngIf="isHiddenfirst" class="ELEMENTTOSHOW subMenuShow">
    first
</div>

<button class="BUTTON" (click)="isHiddensecond = !isHiddensecond">
</button>
<div *ngIf="isHiddensecond" class="ELEMENTTOSHOW subMenuShow">
    second
</div>

TS

import {Component} from 'angular2/core';

@Component({
  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  templateUrl: 'src/hello_world.html',
  styleUrls: ['src/hello_world.css']
})
export class HelloWorld {

isHiddenfirst = false;
ishiddensecond = false;
}

https://plnkr.co/edit/BOLCoRY0SmLe8GZT3PUG?p=preview

【讨论】:

  • 谢谢,但这并不是真正的动态。支持我的问题,因为我需要 15 个代表点来支持你的答案:P
  • 我还需要 4 个代表来支持,当我得到它时,我会支持你。如果没有其他人回答,我会检查它作为最佳答案。
  • 我创建了另一个解决方案,使其更具动态性:plnkr.co/edit/dDIwSH6BFwIR0ZI10vlO?p=preview 我认为您的问题是它们都在 isHidden 为真时出现,因为它们都设置为在它为真时显示并在它为真时隐藏假
猜你喜欢
  • 1970-01-01
  • 2018-03-06
  • 2017-07-11
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
相关资源
最近更新 更多