2

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 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

You know a part of me wondered if using the default property might be an issue but I quickly dismissed it for no good reason. Thanks!
simple answer to a seemingly complicated question..thanks.
worth knowing even though this is not the droid I was looking for..thanks!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.