简体   繁体   English

如何访问 angular 中动态创建的按钮?

[英]How to access dynamically created buttons in angular?

So, I am creating a quiz application where I have a scrollbar for questions and in that scrollbar I have buttons depending on the length of a question set.因此,我正在创建一个测验应用程序,其中我有一个用于问题的滚动条,并且在该滚动条中我有一些按钮,具体取决于问题集的长度。 So I've created those buttons using *ngFor directive.所以我使用 *ngFor 指令创建了这些按钮。 Now what I want to do is whenever a user selects any option (mcq), the question buttons in the scrollbar should get highlighted in following way:现在我想要做的是每当用户选择任何选项 (mcq) 时,滚动条中的问题按钮应该以下列方式突出显示:

  1. If user selects any option, then change the question button color to Green如果用户选择任何选项,则将问题按钮颜色更改为绿色
  2. If user skips the question, then change the question button color to Yellow如果用户跳过问题,则将问题按钮颜色更改为黄色

HTML Code for Question Scrollbar: HTML 问题滚动条代码:

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

I'm have tried doing it by first accessing the buttons using ViewChild in ts file and then apply some logic, but it's not working, it is only changing the color of first button我已经尝试通过首先在 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"
}

How can I achieve my objective?我怎样才能实现我的目标?

You can check for attemptedQuestionCount and change background color like this您可以检查尝试的问题计数并像这样更改背景颜色

<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>

Add button tag as follows:添加按钮标签如下:

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

You can add the click handler directly to the button using您可以使用直接将点击处理程序添加到按钮

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

And then in the component you place the handler然后在组件中放置处理程序

export class AppComponent {
  items = ["hello", "world"]

  heyYouClicked(index){
    console.log("you clicked " + index)
  }
}

You can try ngClass<\/code> for simplicity.为简单起见,您可以尝试ngClass<\/code> 。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM