在 Angular 8 个组件中切换 MatSlideToggle

toggle MatSlideToggle in Angular 8 component

我不断收到此错误:

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

这是我的代码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;
  }

}

test.component.html

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

我做错了什么?这看起来很简单。

如果您尝试在 ngOnInit 上访问它,您的 @ViewChild 未定义。试试这个:

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();
  }

}

如果您不需要在您的组件中引用 MatSlideToggle,您可以直接使用 MatSlideToggle-Directive 的 Input-属性 (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;
}