以角度4更改事件的按钮类

时间:2017-08-01 11:32:51

标签: angular typescript

我正在设计MCQ测试,我想在点击它时将所选按钮选项样式显示为绿色。 我已准备好角度1的代码,但无法将其转换为角度4。 来自Angular 1的代码 -

<div class="row">
                                <table>
                                    <tr ng-repeat="option in question_option.options" class="mtq_clickable col-md-6 col-sm-6">
                                        <td class="mtq_letter_button_td">
                                            <div ng-class="{mtq_css_letter_selected : option.id == question_option.selectedAns}" ng-click="clicked($index+1)" class="mtq_css_letter_button" alt="Question 1, Choice 1">{{option.character}}</div>
                                        </td>
                                        <td class="mtq_answer_td"><label class="divlabel">{{option.text}}</label></td>
                                    </tr>
                                </table>
                            </div>
                    </div>        

enter image description here

Angular 4中的代码

  <table>
                            <tr *ngFor="let options of currentquiz.options" class="mtq_clickable col-md-6 col-sm-6">
                                <td class="mtq_letter_button_td">

                                    <div [ngClass]="{'mtq_css_letter_button': !clicked, 'mtq_css_letter_selected': clicked}" (click)="clicked = true" alt="Question 1, Choice 1">{{options.renderingtext}}</div>
                                </td>
                                <td class="mtq_answer_td">{{options.text}}</td>
                            </tr>

同样我想通过角度4实现。请提出一些想法。目前,当我点击一个按钮时,所有选项样式都变为绿色。

2 个答案:

答案 0 :(得分:0)

嗯,在角度1中,您当前正在保存已单击的选项的ID,而在Angular 4中,您正在更改所有按钮共享的公共变量。

为什么不做与angularjs相同的事情呢?这是一种使用ng-class

中的三元运算符的超快速方法
 <tr *ngFor="let options of currentquiz.options" class="mtq_clickable col-md-6 col-sm-6">
    <td class="mtq_letter_button_td">
       <div [ngClass]="{clicked(option.id) ? 'mtq_css_letter_selected': 'mtq_css_letter_button'}" (click)="click(option.id)" alt="Question 1, Choice 1">{{options.renderingtext}}</div>
    </td>
    <td class="mtq_answer_td">{{options.text}}</td>
 </tr>

在你的component.ts

public clickedId : number;

click(id: number) {
    this.clickedId = id;
}

clicked(id: number): boolean {
   return this.clickedId === id;
}

答案 1 :(得分:0)

在您的选项类/界面中,添加一个单击的变量。然后像这样更改html:

<table>
    <tr *ngFor="let options of currentquiz.options"
    class="mtq_clickable col-md-6 col-sm-6">
        <td class="mtq_letter_button_td">
            <div [ngClass]="{'mtq_css_letter_button': !options.clicked, 'mtq_css_letter_selected': options.clicked}"
            (click)="options.clicked = true"
            alt="Question 1, Choice 1">{{options.renderingtext}}</div>
        </td>
        <td class="mtq_answer_td">{{options.text}}</td>
    </tr>
</table>