如何使用viewchild和elementref更改单击时下拉按钮文本的颜色?

时间:2020-10-27 04:27:17

标签: angular bootstrap-4

使用@ViewchildelementRef单击后,我试图使下拉菜单按钮中的文本更改颜色。这是我的方法,但是不起作用

<div class="dropdown">
    <button class="btn btn-outline-dark dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown"
        (click)="dropdownBtnChangeColor" #dropdownButton>
        Press Me
    </button>
    <div class="dropdown-menu">
        <label class="dropdown-item-text text-dark">Sort By</label>
        <a class="dropdown-item" (click)="onSortByChange(opt.value)">
            <i class="text-center"></i>{{ opt.name }}</a>
        <div class="dropdown-divider"></div>
        <label class="dropdown-item-text">Order By</label>
        <a class="dropdown-item" (click)="onSortDirChange()">
            <i class="text-center"></i>Ascending </a>
    </div>
</div>

这是我的.ts

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

export class MenuComponent implements OnInit {
@ViewChild('dropdownButton', {static: false })
    dropdownButton: ElementRef;

 dropdownBtnChangeColor() {
        this.dropdownButton.nativeElement.setAttribute('style', 'color: green');
   }
}

1 个答案:

答案 0 :(得分:0)

为此,无需使用ViewChildElementRef。您可以像下面这样简单地完成

dropdownBtnChangeColor(event) {
  ((event as MouseEvent).target as HTMLElement).setAttribute(
    "style",
    "background-color : green"
  );
}

仅通过下面的模板传递点击事件

<button ... (click)="dropdownBtnChangeColor($event)">...</button>

工作Stackblitz

如果您仍然想使用ViewChildElementRef,则除了小错误外,您的代码都可以正常工作。也就是说,您在调用()时错过了模板中的dropdownBtnChangeColor。如果将其从dropdownBtnChangeColor更改为dropdownBtnChangeColor(),那么一切都会正常。

工作Stackblitz