如何将css类添加到输入框/单选按钮上单击角按钮



我有模式,即ngx引导模式,其中有两个单选按钮。

如果单击"下一步"按钮,我想在所选单选按钮上获得一个抖动效果作为验证

我已经为shake效果创建了css类。我想添加这个css点击按钮时,它是必需的。我尝试使用ngClass,但它没有按预期工作。如何做到这一点?

HTML

<ng-template #myModal>
<div class="modal-body">
<div class="row">
<div class="col-md-4 col-md-offset-3 text-center">
<input formControlName="genderName" type="radio" id="female" value="Female" [ngClass]="{'rederror': this.cf.genderName.required}">
<label for="female" class="female">Female</label>
</div>
<div class="col-md-4 col-md-pull-1 ml-4">
<input formControlName="genderName" type="radio" id="male" value="Male" [ngClass]="{'rederror': this.cf.genderName.required}">
<label for="male" class="male">Male</label>
</div>
<button type="button" (click)="submit()">Next</button>
</div>
</div>
</ng-template>

css文件

input[type=radio].rederror {
animation: shake 0.5s 3 linear;
border: 1px solid red;
}
@keyframes shake {
0% {margin-left: 0;}
25% {margin-left: 0.5rem;}
75% {margin-left: -0.5rem;}
100% {margin-left: 0;}
}

您可以在提交点击的事件处理程序中添加类。示例工作代码(目标是要将类添加到的任何元素,而不是.col-md-4(-https://stackblitz.com/edit/angular-j94h2r

submit(): void {
const eles = this.formContainer.nativeElement.querySelectorAll('.col-md-4');
eles.forEach(ele => ele.classList.add('shake'));
}

我认为最简单的方法是将抖动效果的样式添加到:active伪选择器中。

input:active {
// css for shaking the radio button
}

您必须在ngClass语句中添加一个检查。

例如,您可以使用与单击相同的复选框。

例如:

<label *ngFor="let radiobutton of radioItems">
<div>
<input type="radio" name="options" (click)="model.option = radiobutton"
[checked]="radiobutton === model.option"
[ngClass]="{'rederror': radiobutton === model.option}">{{radiobutton}}  
</div>
</label>
<p>

查看此工作Stacklitz


编辑这里是您的完整示例:

html:

<div class="modal-body">
<div class="row">
<div class="col-md-4 col-md-offset-3 text-center">
<input formControlName="genderName" type="radio" id="female" (click)="selectedOption=female" value="female"
[ngClass]="{'rederror': selectedOption===female && shake}" [checked]="selectedOption===female">
<label for="female" class="female">Female</label>
</div>
<div class="col-md-4 col-md-pull-1 ml-4">
<input formControlName="genderName" type="radio" id="male" (click)="selectedOption=male"
[checked]="selectedOption===male" [ngClass]="{'rederror': selectedOption===male && shake}">
<label for="male" class="male">Male</label>
</div>
<button type="button" (click)="submit()">Next</button>
</div>
</div>

零部件:

import { Component,  } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public male = "Male";
public female = "Female";
public selectedOption = this.female;
public shake = false;
public submit() {
this.shake = true;    
setTimeout(() => this.shake = false, 500);
}
}

与正在工作的Stacklitz一起!

最新更新