简体   繁体   中英

Angular6: How to add border color to checkbox

I am trying to add border red on an unchecked condition for checkboxes but not working. It is based on .ng-touched.ng-invalid this class name. If it is not selected from the checkboxes then it should be border red color. Now red color is coming for the box but I need check box border only red on unchecked condition. How to do it?

https://stackblitz.com/edit/angular-q7aiwj?file=src/app/app.component.html

app.component.html:

<form [formGroup]="form" (ngSubmit)="submit()">
  <label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
    <input type="checkbox" [formControlName]="i">
    {{ordersData[i].name}}
  </label>

  <div *ngIf="!form.valid">At least one order must be selected</div>
  <br>
  <button type="submit">submit</button>
</form>

You'd need to do a few things to get this done...

  • record input checked somewhere... like inside the ordersData array
  • bind the input with this property using [checked]="ordersData[i].checked" and to record any changes, we do: [(ngModel)]="ordersData[i].checked"
  • next, to style the row, we add a div and give it a [style.border] with condition that if false/un-checked, then display a red box

relevant HTML :

<form [formGroup]="form" (ngSubmit)="submit()">
  <label formArrayName="orders" *ngFor="let order of form.controls.orders.controls; let i = index">
    <div   [style.border]="ordersData[i].checked == false ? '2px solid red' : 'none' "
  >
    <input type="checkbox" [formControlName]="i" [checked]="ordersData[i].checked" [(ngModel)]="ordersData[i].checked"  
    >
    {{i}} -  {{ordersData[i].name}}
  </div>

  </label>

  <div *ngIf="!form.valid">At least one order must be selected</div>
  <br>
  <button type="submit">submit</button>
</form>

Relevant change in TS :

  getOrders() {
    return [
      { id: 100, name: 'order 1', checked:false },
      { id: 200, name: 'order 2', checked:false },
      { id: 300, name: 'order 3', checked:false },
      { id: 400, name: 'order 4', checked:false }
    ];
  }

Complete working stackblitz here

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