简体   繁体   English

角度:单击时更改布尔值

[英]Angular: Change boolean value on click

So, I have a toggle button and a function.所以,我有一个切换按钮和一个功能。 I want that when I click on my button, my boolean value goes from TRUE to FALSE and from FALSE to TRUE .我希望当我点击我的按钮时,我的布尔值从TRUE变为FALSE ,从FALSE变为TRUE And then this value is send to my function.然后这个值被发送到我的函数。

Below you can find the html and ts:您可以在下面找到 html 和 ts:

 <mat-slide-toggle id='stop-camera' (change)='stopCamera($event)'></mat-slide-toggle>

. .

  public stopCamera($event: boolean) : void{
    let num : 0;
    $event =! $event;
    if($event===true){
      console.log('Hi ' +num);
    }else{
      console.log('False');
    }
  }

The problem here is that my console only returns me falses...这里的问题是我的控制台只返回假...

I know it's something really basic and even simple, but because it's so simple and basic I can't find out how to do it... So I would like to get some help please .我知道这是一些非常基本甚至简单的东西,但是因为它是如此简单和基本,我无法找到如何去做...所以我想得到一些帮助。 I thank in advance anyone who will take the time to help me.我预先感谢任何愿意花时间帮助我的人。

PS: I'm on Angular 9 right now. PS:我现在在 Angular 9 上。

1.component.html 1.component.html

 <mat-slide-toggle id='stop-camera' (change)='stopCamera($event)'></mat-slide-toggle>

2.Mat-Slide toggle will give you the events when toggle changes no need to put ! 2.Mat-Slide 切换将在切换更改时为您提供事件,无需放置! condition状况

public stopCamera(event:any) : void{
    let num : 0;
    if(event.checked){
      console.log('Hi' +num);
    }else{
      console.log('False');
    }
  }

You might want to define a variable/state that will update on button click您可能想要定义一个将在单击按钮时更新的变量/状态

toggleState = true切换状态 = 真

(click) = 'toggleState()' (点击) = 'toggleState()'

public toggleState(){
  this.toggleState = !this.toggleState
}

You can access the variable in any function you want in your component.您可以在组件中所需的任何函数中访问该变量。

One possible way is to use two-way data binding with NgModel .一种可能的方法是对NgModel使用双向数据绑定。 Your template:您的模板:

<mat-slide-toggle [(ngModel)]="checked" (ngModelChange)="toggle()">
  Toggle
</mat-slide-toggle>

Your component:您的组件:

checked = true;

toggle(): void {
  console.log(this.checked);
  // do more stuff
}

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

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