一次只将一个div应用于所选的样式(没有jQuery)

时间:2018-06-19 07:48:49

标签: javascript html angular

你能帮我吗?当我点击带有class =“role-box”的div时,我需要使<span class="badge badge-light"><i class="fa fa-check-circle"></i></span>可见(最初它具有样式“visibility:hidden”)。它应该以下列方式工作:当我点击标题为“Role-one”的div时,此div的徽章将可见,如果我点击标题为“Role-two”的div,则为“角色一”div将被隐藏,“角色二”div的徽章将可见。目前,如果我点击它们,它会显示所有div的徽章。以下是代码。

HTML:

<div class="col-6 col-md-4" *ngFor="let role of joblabels, index as ri">
    <div class="role-box" id="{{ri}}" (click)="selectRole(ri)">
        <span class="badge badge-light"><i class="fa fa-check-circle"></i></span>
        <p class="role-type">{{ role.title }}</p>
    </div>
</div>

TS:

joblabels = [
{title: 'Role-one'}, 
{title: 'Role-two'}, 
{title: 'Role-three'}];


selectRole(id) {
let badge = document.getElementById(id).childNodes;
if (badge[1]['style'].visibility === 'visible') {
  badge[1]['style'].visibility = 'hidden';
}
else {
  badge[1]['style'].visibility = 'visible';
} }

1 个答案:

答案 0 :(得分:2)

您可以使用角度的[ngStyle]。

拥有一个包含所选

状态的变量

组件TS:

selectedRole: any;

joblabels = [
{title: 'Role-one'}, 
{title: 'Role-two'}, 
{title: 'Role-three'}];


selectRole(title) {
  this.selectedRole = title;
}

HTML:

<div class="col-6 col-md-4" *ngFor="let role of joblabels, index as ri">
    <div class="role-box" id="{{ri}}" (click)="selectRole(role.title)">
        <span class="badge badge-light" [ngStyle]="{'visibility':role.title === selectedRole ? '' : 'hidden' }"><i class="fa fa-check-circle"></i></span>
        <p class="role-type">{{ role.title }}</p>
    </div>
</div>