Jonathan
Jonathan

Reputation: 4689

toggle MatSlideToggle in Angular 8 component

I keep getting this error:

"ERROR TypeError: Cannot set property 'checked' of undefined"

Here is my code test.component.ts:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSlideToggle } from '@angular/material/slide-toggle';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  @ViewChild('testSlider', { static: false }) t: MatSlideToggle;

  constructor() { }

  ngOnInit() {
    this.t.checked = true;
  }

}

And test.component.html

<mat-slide-toggle #testSlider>Test</mat-slide-toggle>

What am I doing wrong? This seems simple.

Upvotes: 2

Views: 1976

Answers (2)

Matthias Good
Matthias Good

Reputation: 11

If you don't need a reference of the MatSlideToggle in your component you can directly use the Input-Property of the MatSlideToggle-Directive (https://material.angular.io/components/slide-toggle/api).

test.component.html

<mat-slide-toggle [checked]="toggleChecked">Test</mat-slide-toggle>

test.component.ts

export class TestComponent { 
  toggleChecked = true;
}

Upvotes: 1

Constantin Beer
Constantin Beer

Reputation: 5835

Your @ViewChild is not defined if you try to access it on ngOnInit. Try this:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSlideToggle } from '@angular/material/slide-toggle';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements AfterViewInit {

  @ViewChild('testSlider', { static: false }) t: MatSlideToggle;

  constructor(private changeDetectorRef:ChangeDetectorRef) { }

  ngAfterViewInit() {
    this.t.checked = true;
    this.changeDetectorRef.detectChanges();
  }

}

Upvotes: 2

Related Questions