如果条件为复选框3的倍数 [英] if condition for multiple of 3 for check box
问题描述
当用户在复选框中第三次点击时,它应显示红色。
它应该循环。
你能告诉我如何实现它。
提供我的代码低于
如果条件为3的倍数但它不工作
https://stackblitz.com/edit/angular-c8ggww?file=app/app.component.ts
$ ('click',function(){
counter = counter + 1;
console.log(
pre $
$('#buttonId')。 ('counter --->'+ counter);
if(counter%3 == 0){
// apply new style
console.log('multiple of 3-- - >'+ counter);
$('#buttonId').css('background-color','red');
}
});
首先,您不应该在Angular中使用jQuery进行DOM操作。
其次,你在Angular中附加你的点击处理程序(在模板中使用(点击)
),然后在jQuery中添加另一个元素(在组件类中使用 .click()
方法)。
你应该做什么是摆脱jQuery,只使用(点击)
Angular指令,然后使用Angular的 ngClass
在条件上应用一个类。
TS
public open(event){
this.count = this.count + 1;
console.log('this.count --->'+ this.count);
if(this.count%3 == 0){
console.log('3的倍数 - >'+ this.count);
this.multipleOf3 = true;
} else {
this.multipleOf3 = false;
code
$ b HTML
< label [ngClass] ={'is-multiple-of-3':multipleOf3}>
< input type =checkboxname =rememberLoginid =buttonId(click)=open()>点击我
< / label>
CSS
.is-multiple-of-3 {
background-color:#f00;
}
这是 更新的闪电战 。
关于ngClass
< label [ngClass] ={'is-multiple-of-3':multipleOf3}>
以上代码表示:将类is-multiple-of-3应用于当前元素是表达式 multipleOf3
是true(或者JavaScript中的truthy)。 更多资讯正式的Angular文档。
when user clicks third time in the checkbox it should show red color.
it should go in a loop.
can you tell me how to achieve it.
providing my code below
I used if condition for multiple of 3 but its not working
https://stackblitz.com/edit/angular-c8ggww?file=app/app.component.ts
$('#buttonId').on('click', function() {
counter = counter + 1;
console.log('counter--->' + counter);
if (counter % 3 == 0) {
// apply new style
console.log('multiple of 3--->' + counter);
$('#buttonId').css('background-color', 'red');
}
});
解决方案 First you should not use jQuery for DOM manipulation in Angular.
Second, you are attaching your click handler in Angular (with (click)
in the template) and then add another in jQuery (with the .click()
method in your component class).
What you should do is get rid of jQuery and use only the (click)
Angular directive then use Angular's ngClass
to apply a class conditionnally.
TS
public open(event) {
this.count = this.count + 1;
console.log('this.count--->' + this.count);
if (this.count % 3 == 0) {
console.log('multiple of 3--->' + this.count);
this.multipleOf3 = true;
} else {
this.multipleOf3 = false;
}
}
HTML
<label [ngClass]="{'is-multiple-of-3':multipleOf3}">
<input type="checkbox" name="rememberLogin" id="buttonId" (click)="open()"> click me
</label>
CSS
.is-multiple-of-3 {
background-color: #f00;
}
Here is an updated blitz.
About ngClass
<label [ngClass]="{'is-multiple-of-3':multipleOf3}">
The code above means : apply the class "is-multiple-of-3" to the current element is the expression multipleOf3
is true (or "truthy" in JavaScript).
More info in the official Angular documentation.
这篇关于如果条件为复选框3的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!