Angular 6 *ngSwitchCase 不工作

Angular 6 *ngSwitchCase Not Working

示例:我正在使用 div 容器,当我 运行 代码时,我只得到 是开关默认值。

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-test',
template: `  
          <div [ngSwitch]="toy_color">
             <div *ngSwitchCase="'red'"> RED </div>
             <div *ngSwitchCase="'blue'">  BLUE </div>
             <div *ngSwitchCase="'Yellow'"> YEllOW </div>
             <div *ngSwitchDefault> Pick Again </div>
          </div>

          `
styles: []
})
export class TestComponent implements OnInit {

 public toy_color:"red";

constructor() { }

ngOnInit() { }
}

您的变量 toy_color 未定义。将其更改为以下行:

public toy_color: string = "red";

public toy_color = "red";

您的代码中的以下行不正确。

public toy_color:"red";

您没有为 toy_color 赋值。您应该使用它的类型更改您的代码,或者您可以直接为变量赋值,如下所示。

  1. 有分配类型

public toy_color: string = "red";

  1. 直接赋值

public toy_color = "red";

我创建了一个demo供您参考。