Reputation: 4689
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
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
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