2
votes

I have a "parent" component whose template includes two other components. I want to show or hide either component somehow. I looked at the multiple component angular.io tutorial to try and figure this out but nothing is happening (and no console errors are coming up).

My "parent" component with it's template is:

@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>

My child components each have a template but here are what the code looks like in them.

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;
}

When the page loads with it's MainComponent child2 should be hidden (with it's template) and child1 shown (with it's template). However both are being shown. I've tried creating a button with a (click)=setHidden() function on the MainComponent to change the MainComponent properties but nothing happens. What am I missing when it comes to the inter-component communication?

2

2 Answers

4
votes

hidden is a default property. Adding an input with the same name seems to prevent the default behavior. Commenting out the input makes hidden work:

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

Plunker

1
votes

The accepted answer is fine but directives has now been deprecated so if you use the code as originally stated in Angular4 then you will get an error.

As long as the child components are declared within @NgModule in the module, they no longer need to to be included in the metadata of the parent component