【问题标题】:How to access dynamically created buttons in angular?如何以角度访问动态创建的按钮?
【发布时间】:2022-02-17 23:46:57
【问题描述】:

所以,我正在创建一个测验应用程序,其中有一个问题滚动条,并且在该滚动条中我有一些按钮,具体取决于问题集的长度。所以我使用 *ngFor 指令创建了这些按钮。现在我想做的是,每当用户选择任何选项(mcq)时,滚动条中的问题按钮应该以下列方式突出显示:

  1. 如果用户选择任何选项,则将问题按钮颜色更改为绿色
  2. 如果用户跳过问题,则将问题按钮颜色更改为黄色

问题滚动条的 HTML 代码:

<div id="answer-buttons" class="ques-grid ">
            <button #navBarButton *ngFor="let item of items">{{item}}</button>
</div>

我已经尝试通过首先使用 ts 文件中的 ViewChild 访问按钮然后应用一些逻辑来做到这一点,但它不起作用,它只是改变了第一个按钮的颜色

@ViewChild('navBarButton',{ static: false }) navBarButton:ElementRef
//and in some function I've tried this logic
if(this.attemptedQuestionCount[this.currentQuestionIndex]==1){
  this.navBarButton.nativeElement.style.backgroundColor = "#228B22"
}
else{
  this.navBarButton.nativeElement.style.backgroundColor = "#FCF55F"
}

我怎样才能实现我的目标?

【问题讨论】:

  • ViewChild 仅获取一个唯一元素(第一个),如果您想获得所需的一切,请使用 @ViewChildren -返回元素的 QueryList。

标签: javascript html angular typescript mean-stack


【解决方案1】:

您可以检查尝试的QuestionCount 并像这样更改背景颜色

<div id="answer-buttons" class="ques-grid ">
<button *ngFor="let question of questions; let i=index"
    [style.background-color]="attemptedQuestionCount[i] === 1 ? '#228B22' : '#FCF55F'">{{question}}</button>
</div>

【讨论】:

  • 谢谢伙计!你真棒。
【解决方案2】:

添加按钮标签如下:

<button *ngFor="let question of questions; let i=index"
        [style.background-color]="attemptedQuestionCount[i] === 1 ? '#228B22' : '#FCF55F'">{{question}}</button>

【讨论】:

    【解决方案3】:

    您可以使用直接将点击处理程序添加到按钮

    <button *ngFor="let item of items; let indexOfelement=index" 
          (click)="heyYouClicked(indexOfelement)">{{item}}</button>
    

    然后在组件中放置处理程序

    export class AppComponent {
      items = ["hello", "world"]
    
      heyYouClicked(index){
        console.log("you clicked " + index)
      }
    }
    

    【讨论】:

    • 这是我已经尝试过但在我的情况下不起作用的东西
    • 也许您还有其他一些不在您的问题中的有问题的代码?此示例适用于代码沙箱:codesandbox.io/s/buttons-demo-kukw5
    【解决方案4】:

    为简单起见,您可以尝试ngClass

    <button #navBarButton *ngFor="let item of items" class="defualt_state" [ngClass]="{'new_state': (condition_here)}">{{item}}</button>
    

    在样式表中你可以配置上面的类

    .new_state { background-color: #228B22 !important }
    

    并以这种方式设置按钮的默认颜色

    .default_state { background-color : #FCF55F}
    

    因此,当条件匹配时,它将采用 new_state 类中指定的颜色,否则将采用 default_state 类中的默认颜色。

    【讨论】:

      最近更新 更多