angular 2隐藏或显示子组件

时间:2016-03-22 19:16:56

标签: angular

我有一个“父”组件,其模板包含另外两个组件。我想以某种方式显示或隐藏任一组件。我看了multiple component angular.io tutorial试图弄清楚但没有发生任何事情(并且没有出现控制台错误)。

我的“父”组件及其模板是:

@Component({
    selector: 'main-area',
    templateUrl: 'main-area.html',
    directives: [Child1Component, Child2Component]
})
export class MainComponent {
        child1Shown:boolean = true;
        child2Shown:boolean = false;
}

main-area.html -

<div>
    <childOne [hidden]="child1Shown"></childOne>
    <childTwo [hidden]="child2Shown"></childTwo>
</div>

我的子组件每个都有一个模板,但这里是代码的样子。

Child1:

@Component({
    selector:'childOne',
    templateUrl: 'childOne.html'     
})    

export class Child1Component { 
   @Input() hidden:boolean;
}

CHILD2:

@Component({
    selector: 'childTwo',
    templateUrl: 'childTwo.html'
})

export class Child2Component {
        @Input() hidden:boolean;
}

当页面加载时,应隐藏MainComponent child2(使用它的模板)并显示child1(使用它的模板)。但两者都在展示。我尝试在MainComponent上创建一个带有(click)=setHidden()函数的按钮来更改MainComponent属性,但没有任何反应。在组件间通信方面我缺少什么?

2 个答案:

答案 0 :(得分:4)

hidden是默认属性。添加具有相同名称的输入似乎可以防止默认行为。注释掉输入会使hidden工作:

export class Child2Component {
    // @Input() hidden:boolean;
}

Plunker

答案 1 :(得分:0)

接受的答案很好,但directives现已被弃用,所以如果您使用Angular4中最初声明的代码,那么您将收到错误。

只要子模块在模块中的@NgModule中声明,就不再需要将它们包含在父组件的元数据中

相关问题