2017-07-21 44 views
0

我想讓ngSwitch動態顯示和隱藏組件,但ngSwitch似乎沒有工作。ngSwitch不能使用字符串

我創建了這個問題的simplifed版本與此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> 

這是我的打字稿文件:

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

} 

怪異的事情是我的開關正在尋找值「輸入」,即使它的定義,它仍然生成空綁定

enter image description here

+0

嘗試'* ngSwitchCase = 「 '達賴喇嘛'」'。 –

回答

2

你應該有它裏面''

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

謝謝我剛剛意識到這一秒之前,我希望它會警告我 –

+0

@ johnny5問題是它不知道你是否打算使用字符串文字,或者你是否打算使用一個變量,但忘記定義它。 –

+0

是的,我希望它會給我一個警告,我使用了一個未定義的變量 –