Set indeterminate on Angular checkbox

前端 未结 2 1946
轮回少年
轮回少年 2021-01-23 15:20

I\'m trying to programatically set the value of Angular checkboxes to either, false true or indeterminate. I understand that I cannot set

相关标签:
2条回答
  • 2021-01-23 15:45

    To make a checkbox indeterminated, you can use a directive

    import { Directive, ElementRef,Input } from '@angular/core';
    
    @Directive({ selector: '[indeterminate]' })
    export class IndeterminateDirective {
       @Input() 
       set indeterminate(value)
       {
         this.elem.nativeElement.indeterminate=value;
       }
        constructor(private elem: ElementRef) {
        }
    }
    

    Then you're checkbox can be like

    <input class="pull-left" type="checkbox" 
         [indeterminate]="client.indeterminated" 
         [checked]="client.checked" (click)="click(client)"/>
    

    where

      click(cliente: any) {
        let indeterminated=(!cliente.checked && !cliente.indeterminated) ? true : false;
        let checked=(!cliente.checked && cliente.indeterminated)?true:false
        cliente.indeterminated = indeterminated;
        cliente.checked=checked;
      }
    

    See that you have two variables "checked" and "indeterminated", you can make a cycle as you want

    0 讨论(0)
  • 2021-01-23 16:05

    Yes, you can use [indeterminate]="condition" (without any directives). You can't do indeterminate="{{condition}}". The difference is that [...] sets property of the element, while without brackets you are setting attribute. HTMLInput element has property indeterminate, but doesn't have such attribute.

    In order use ngModel or FormControl, which holds simultaneously the both checked and indeterminate states, you should create a custom directive or/and additional logic in your primary component (for reference, see the answer from @Eliseo).

    Q1. How can I cycle through these three state in the same way as you can with gmail?

    Handle clicks, change state of the pair "checked" and "indeterminate" in cycle. Example with jQuery.

    Q2. Why am I getting the ExpressionChangedAfterItHasBeenCheckedError with the current setup?

    You have side effect in the checkedLabels method, which changes state of the component, each time Angular checks value of the expression [indeterminate]="checkedLabels()".

    0 讨论(0)
提交回复
热议问题