简体   繁体   中英

Checkbox checked if the value is true in angular 4

I have a checkbox when on certain condition we need to make the checkbox checked.For eg Whenever accept() function calls, it triggers onApprovedDateChecked() function by passing true as a parameter.Whenever i get true i need to make the checkbox to be checked.Can anyone help me to sort this out??

component.html

 <p-checkbox label="dsd" formControlName="fcont" binary="true" 
                               (onChange)="onChecked($event)"></p-checkbox>

component.ts

    accept(){
      onChecked(true)
    }

   onChecked(e: any){

     //make the checkbox to checked
   }
<p-checkbox label="dsd" [(ngModel)]="status" 
formControlName="fcont" binary="true"(onChange)="onChecked($event)"></p-checkbox>

Now define status before constructor like this in your ts file

    import { Component, OnInit } from '@angular/core';
    import {ActivatedRoute, Router} from '@angular/router';

    @Component({
      selector: 'component',
      templateUrl: './component.html',
      styleUrls: ['./component.scss']
    })
    export class RequestReturnComponent implements OnInit {
    status: boolean = false;
    constructor() {}

    ngOnInit() {}

    accept(){
     onChecked(true)
    }

    onChecked(e: any){
      this.status = true;
    }
  }

Use ngModel with binary to change its boolean value

<p-checkbox label="dsd" [(ngModel)]="obj.status" 
formControlName="fcont" binary="true"(onChange)="onChecked($event)"></p-checkbox>

Set obj.status to true or false to change.

accept(){
 onChecked(true)
}

onChecked(e: any){
  this.obj.status = true;
}

You may like the async pipe for this, the implementation for this would look like this

@Component({
  selector: 'async-checkbox-pipe',
  template: '<input type="checkbox" [checked]="onApprovedDateChecked | async" /> Async checked'
})
export class AsyncCheckboxPipeComponent {
  onApprovedDateChecked = new Observable<string>((observer: Observer<string>) => {
    // use the observer to dispatch checked or not later on
      setTimeout(() => {
        return observer.next(true|false)
      }, 1500);
  });
}

Example here https://stackblitz.com/edit/angular-8cqcph

HTML

<p-checkbox label="dsd" [checked]="checkValue" formControlName="fcont" (onChange)="onChecked($event)">
</p-checkbox>

component.ts

//declare variable

checkValue:boolean = false;

---function---

accept(){
checkValue = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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