Search code examples
cssangulartypescriptangular-materialangular-directive

Angular Material Slide Toggle not changing bound variable


I have 2 strange problems. I have a large form with lots of input fields. That works fine. I want to add a slide toggle at the bottom which changes a variable that will affect styles on the whole form.

My first problem is that the variable will not display until the slide toggle is clicked.

HTML

<mat-slide-toggle [(ngModel)]="ifPrint" name="ifPrint" id="ifPrint" ></mat-slide-toggle>

<div>
  {{ifPrint}}
</div>

COMPONENT

export class PrintReviewDetailsComponent implements OnInit {
ifPrint = true;
}

the ifPrint variable is blank on page load

The second problem is

when the slide toggle is clicked the div containing the variable shows as true but when I click the toggle to the off position the ifPrint variable stays as true and does not change.

I have created a blitz and it is working fine there with the same code so I am unsure as why I am having these issues on my page.

The console says:

Error: No value accessor for form control with name: 'ifPrint'

EDIT: I updated the stackblitz to include the html of the form and now it is not working.


Solution

  • Your updated stackblitz couldn't recreate the issue which you shared... But from your question, the following 2 issues are addressed for a form and styling is also done:

    • the toggle value was not displayed by-default until the toggle was clicked
    • the toggle value didn't change when you toggled it
    • the style is now being updated based on the toggle value

    relevant TS:

      model:any;
      constructor(){
        this.model = {name: '' , age: null, ifPrint: false};
      }
    

    relevant HTML:

    <form (ngSubmit)="formSubmit()" #demoForm="ngForm"  >
      <div [ngClass]="model.ifPrint === true ? 'trueClass' : 'falseClass'">
      <input type="text"  placeholder="Enter Name" #name="ngModel" [(ngModel)]="model.name" name="name" />
       <br/>
      <input type="number"  placeholder="Enter Age" #age="ngModel" [(ngModel)]="model.age" name="age" />  <br/>
      <mat-slide-toggle #ifPrint #age="ngModel" [(ngModel)]="model.ifPrint" name="ifPrint"></mat-slide-toggle> {{model.ifPrint}} <br/>
      </div>
    <button type="submit"> Submit </button>
    </form>
    

    check a minimal, working demo here for what you're trying... hope it helps...