ngSwitch不支持字符串类型的值。

14
我试图使用ngSwitch来动态地显示和隐藏组件,但是ngSwitch似乎无法正常工作。
我使用plunker创建了一个简化版本的这个问题。
这是组件的HTML代码:
<div [ngSwitch]="componentType">
  <div *ngSwitchCase="input">
    <div>Rendered</div>
    <ion-item [hidden]="editOptions.isEditing">
      <ion-note color="primary">{{label}}</ion-note>
      <ion-note class="inline-edit"> {{value}}&nbsp;</ion-note>
    </ion-item>
    <ion-item [hidden]="!editOptions.isEditing">
      <ion-label color="primary">{{label}}</ion-label>
      <ion-input [(ngModel)]="value" [required]="required" [type]="type" [name]="value"></ion-input>
    </ion-item>
  </div>
  <div *ngSwitchCase="Lama"><div>Rendered</div></div>
</div>

这是我的 TypeScript 文件:

import {
    Component,
    Input,
    ElementRef,
    ViewChild,
    Renderer,
    forwardRef,
    OnInit
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { EditOptions } from '../../../models/editOptions';

const INLINE_EDIT_CONTROL_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => InlineEditComponent),
    multi: true
};

@Component({
  selector: 'inline-edit',
  templateUrl: 'inline-edit.html',
  providers: [INLINE_EDIT_CONTROL_VALUE_ACCESSOR],
})
export class InlineEditComponent implements ControlValueAccessor, OnInit {

    @ViewChild('inlineEditControl') inlineEditControl: ElementRef;
    @Input() label: string = '';
    @Input() type: string = 'text';
    @Input() componentType: string = 'input';
    @Input() required: boolean = false;
    @Input() disabled: boolean = false;
    @Input() editOptions: EditOptions;
    private _value: string = '';
    private preValue: string = '';
    public onChange: any = Function.prototype;
    public onTouched: any = Function.prototype;

    get value(): any {
        return this._value;
    }

    set value(v: any) {
        if (v !== this._value) {
            this._value = v;
            this.onChange(v);
        }
    }

    writeValue(value: any) {
        this._value = value;
    }

    public registerOnChange(fn: (_: any) => {}): void {
        this.onChange = fn;
    }

    public registerOnTouched(fn: () => {}): void {
        this.onTouched = fn;
    }

    constructor(element: ElementRef, private _renderer: Renderer) {
    }

    ngOnInit() {
    }

}
奇怪的是,我的开关正在寻找值“input”,即使它在情况下被定义,它仍然生成了空绑定。


尝试使用 *ngSwitchCase="'Lama'" - user663031
1个回答

32

你应该将它放在''里面

<div *ngSwitchCase="'input''>
<div *ngSwitchCase="'Lama'"><div>Rendered</div></div>

1
谢谢,我刚刚意识到这个问题,但我希望它能提醒我。 - johnny 5
1
@johnny5 问题在于它不知道你是想使用字符串字面量,还是忘记定义变量了。 - John Montgomery
1
是啊,我希望它能警告我正在使用未定义的变量。 - johnny 5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接