代码之家  ›  专栏  ›  技术社区  ›  Jonathan

在角度8组件中切换MatslideToggle

  •  0
  • Jonathan  · 技术社区  · 5 年前

    我一直有这个错误:

    “错误类型错误:无法设置未定义的”“checked”“属性”

    这是我的密码 测试组件 :

    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>
    

    我做错什么了?这似乎很简单。

    1 回复  |  直到 5 年前
        1
  •  0
  •   Constantin Beer SDC    5 年前

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

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