我想在单击关闭按钮Angular 6后隐藏div

时间:2019-07-24 11:35:20

标签: javascript typescript angular6

我想在Angular 6中单击关闭按钮后隐藏div,而其他人想要更改其他div类。

例如另一个div类是col-sm-7,单击关闭按钮后,它将更改为col-sm-12

在我的component.html

<div id="custom-div">
 <button class="close" type="button" click="featureHide()">X</button>
</div>
<div id="another-div" class="col-sm-7"></div>

在我的component.ts

featureHide() {
  document.getElementById('custom-div').style.display='none';
  var element = document.getElementById("another-div");
  element.classList.add("col-sm-12");
}  

但是它不起作用,请提出建议。

3 个答案:

答案 0 :(得分:1)

我建议改用Angular [ngClass]指令:

这里有一个stackblitz working example(切记要扩展浏览器标签以超过sm断点)

  //Apply [hidden] to hide the button
<div id="custom-div" [hidden]="!isShow" >
  // Use '(click)' instead of 'click' 
  <button class="close" type="button" (click)="featureHide()">X</button>
</div>
  //Apply [ngClass] directive
<div id="another-div" [ngClass]="{'col-sm-7': isShow , 'col-sm-12': !isShow }"></div>

在您的ts文件中:

isShow = true;

featureHide() {
 this.isShow= false;
};

也可以按照您尝试的方式进行操作,但是先将click更改为(click),然后在ts中输入

featureHide() {
  document.getElementById('custom-div').style.display = 'none';
  const element = document.getElementById("another-div");
  element.classList.remove("col-sm-7");
  element.classList.add("col-sm-12");
}  

答案 1 :(得分:0)

您的方法在角度上是错误的。尽量避免使用document.xxx,请使用angular.xxx。 请找到以下代码

在component.html

<div id="custom-div">
<button class="close" type="button" (click)="featureHide()">X</button>
</div>
<div *ngIf="hideFalg" id="another-div" class="col-sm-7"></div>

在我的component.ts中     hideFalg:Boolean = true

featureHide()
{
  this.hideFalg = false; // this code will hide the div element since we have added the *ngIf
}

显示div

showDiv(){
this.hideFalg = true;
}

答案 2 :(得分:-1)

这是一个工作示例。

  1. 点击的用法应类似于(点击)
  2. 使用ngGlass

组件样本

<div id="custom-div">
    <button class="close" type="button" (click)="featureHide()">X</button>
</div>
<div *ngIf="isShow" id="first-div">First Div</div>
<!--You can also use hidden. Be careful with the variable name and value. This could get confusing.-->
<div [hidden]="!isShow">First-1 Div</div> 
<div id=" another-div" [ngClass]="{'col-sm-7': isShow , 'col-sm-12': !isShow }">Second Div</div>

在您的TS中

isShow = true;
featureHide() {
    this.isShow = !this.isShow
}