【问题标题】:I want to do DOM manipulation like we do in jquery but in Angular 6我想像在 jquery 中但在 Angular 6 中那样进行 DOM 操作
【发布时间】:2020-03-02 23:22:40
【问题描述】:

我想通过点击按钮来改变父 div 的背景颜色。

<div>
    <p>I want to change the background-color of the parent div by the click of the button.
    </p>
   <button (click)="changeColour()" id="buy-now">BUY NOW</button>
<div>

【问题讨论】:

    标签: angular typescript angular6 dom-manipulation


    【解决方案1】:

    不要把它想象成 JQuery!

    但更详细的答案:

    您的 HTML 将使用类的表达式

    <div [ngClass]="{'blue' : isBlue }"> 
        <p>I want to change the background-color of the parent div by the click of the button.
        </p>
       <button (click)="changeColour()" id="buy-now">BUY NOW</button>
    <div>
    

    然后您的 TypeScript 将切换该值。您还可以根据需要使用表达式/类名:

    export class AppComponent  {
    isBlue = false;
      changeColour() {
        this.isBlue = !this.isBlue;
        console.log(this.isBlue);
      }
      name = 'Angular';
    }
    

    See working example:

    【讨论】:

    • 不是这样的,你是在改变isBlue的值,假设它在很多div中,那怎么办?
    • @FurquanSaifi 然后你可以使用一个数组,或者数组上的一个表达式,或者自定义模块/指令,这样每个 div 都是它自己的对象,具有你关心的属性。这 你应该接近它的方式,直接 DOM 操作是不好的。此外,您的代码甚至没有建议您正在使用的模型或许多潜在的 div。
    【解决方案2】:

    您可以有条件地向父div添加一个类([class.red]="isRed"),并在调用changeColor()函数时更改条件(isRed = true)。

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多