【问题标题】:Angular 6 - How to disable a div based on conditionAngular 6 - 如何根据条件禁用 div
【发布时间】:2019-10-27 06:30:01
【问题描述】:

我有一个 div 会在单击按钮时展开,当我再次单击该 div 时,它将是可单击的或会出现警报,但是当我单击展开的(100%)视图时它不应该是可单击的,它应该就像禁用一样。当我再次返回上一个(25%)视图时,div 应该是可点击的。任何人都可以帮助我。 下面是代码

app.component.html

<button (click)="change()">change</button>
<div (click)="expand()" [ngClass]="{'old': toggle, 'new': !toggle}"class="old">
  Hello
</div>

app.component.ts

declare var require: any;
import { Component,OnInit, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
    toggle:boolean = true;
  ngOnInit(){

  }
change(){
    this.toggle = !this.toggle;
  }
expand(){
    alert('hi');
  }
}

style.css

.old{
    width:25%;
    border:1px solid;
    height:200px;
    cursor:pointer;
    background:yellow;
}
.new{
    width:100%;
    border:1px solid;
    height:200px;
    cursor:pointer;
    background:green;
}

【问题讨论】:

  • 我认为这个问题的标题有歧义,问题可以简化。提供的 .css 代码无助于理解问题。

标签: html css angular typescript


【解决方案1】:

更改您的文件,如下所示:

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

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

  public toggle: boolean = true;

  ngOnInit(): void {

  }

  public change(): void {
    this.toggle = !this.toggle;
  }

  public expand(): void {
    if (this.toggle) {
      alert('hi');
    }
  }

}

还有你的 html 文件:

<button (click)="change()">change</button>
<div (click)="expand()" [class.new]="!toggle" class="old">
    Hello
</div>

【讨论】:

    【解决方案2】:

    试试这个:

    <button (click)="change()">change</button>
    <div  [class.disabled]="!toggle"  (click)="toggle && expand()" [ngClass]="{'old': toggle, 'new': !toggle}"class="old">
      Hello
    </div>
    

    在 CSS 中:

    .disabled {
      cursor: not-allowed;
    }
    

    Working Demo

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 2020-05-30
      • 1970-01-01
      • 2019-01-17
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2011-04-26
      相关资源
      最近更新 更多