2016-11-21 32 views
0

我有一个侧边栏和一个按钮,单击时我想切换变量true或false,然后显示/隐藏兄弟组件。我收到错误Type '{}' is not assignable to type 'boolean'。我如何才能以正确的方式实现这一目标?打开关闭同级组件

侧边栏-menu.component.ts

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

@Component({ 
    selector: 'sidebar-menu', 
    templateUrl: './sidebar-menu.component.html', 
    styleUrls: ['./sidebar-menu.component.styl'] 
}) 
export class SidebarMenuComponent { 

    showDetails = false; 
    @Output() 
    onShowDetails: EventEmitter<boolean> = new EventEmitter(); 

    constructor() {} 

    toggleDetails() { 
    this.showDetails = !this.showDetails; 
    this.onShowDetails.emit(this.showDetails); 
    console.log('Sidebar Toggle', this.showDetails); 
    } 

} 

details.component.ts

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

@Component({ 
    selector: 'details', 
    templateUrl: './details.component.html', 
    styleUrls: ['./details.component.styl'] 
}) 
export class DetailsComponent { 

    @Input() showDetails: boolean; 

    constructor() { 

    } 

} 

app.component.ts

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

@Component({ 
    selector: 'app', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.styl'] 
}) 
export class AppComponent { 
    @Input() showDetails: boolean = false; 


    constructor() { 
    } 

} 

app.component.html

<sidebar-menu></sidebar-menu> 
<details *ngIf="showDetails"></details> 
<router-outlet></router-outlet> 
+0

您声明showDetails作为EventEmitter,右后,在构造函数中,你将它初始化为假。 false对于EventEmitter类型的变量不是有效的值。不确定信息如何更清晰。 –

+0

是的,很明显,我不能使用布尔值,这很明显。什么不是为什么,我能做些什么呢。我如何在两个组件之间推送真/假值。 – Daimz

+0

使用你的事件发射器来发射事件。从父组件收听这些事件以更改详细信息组件的showDetails输入的值。 –

回答

1

你showDetails属性不是布尔类型,它是EventEmitter<boolean>类型,当你试图像this.showDetails = false;达到设定值时,它抛出错误。 试试这个:

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

@Component({ 
    selector: 'sidebar-menu', 
    templateUrl: './sidebar-menu.component.html', 
    styleUrls: ['./sidebar-menu.component.styl'] 
}) 
export class SidebarMenuComponent { 

    showDetails = false; 
    @Output() 
    onShowDetails: EventEmitter<boolean> = new EventEmitter<boolean>(); 

    constructor() {  
    } 

    toggleTeamDetails() { 
    this.showDetails = !this.showDetails; 
    this.onShowDetails.emit(this.showDetails); 
    console.log('Sidebar Toggle', this.showDetails); 
    }  
} 

和兴趣在此事件应该订阅此事件的组件。

另外如果你想直接在模板中使用布尔值,你可以这样做:

<sidebar #sidebar> 
    <child-component *ngIf="sidebar.showDetails"></child-component> 
</sidebar> 
<sibling-component *ngIf="sidebar.showDetails"></sibling-component> 
+0

我走了,上面更新了代码。我现在得到这个错误'类型'EventEmitter <{}>'不能分配给类型'EventEmitter '。 类型'{}'不能分配给'boolean'类型。' – Daimz

+0

另外我的补充工具栏和细节组件都是应用程序组件的子项,而不是彼此的,所以我不确定这将如何与'#侧边栏#'配合使用。 – Daimz

+0

我忘了添加<>到EventEmitter,请参阅更新的代码。你也可以在兄弟节点中使用#变量。所以它看起来像: Nikolai