简体   繁体   中英

Use case for private components

I'm trying to come up with a simple use case for private components and here it it. Suppose I have the module HelloWorldAppModule with one public and one private component:

@Component({
    selector: 'hello-world',
    template: `
    <div>
        <private></private>
    </div>`
})
class HelloWorldComponent {
}

@Component({
    selector: 'private',
    template: `<span>I am private</span>`
})
class PrivateComponent {
}


@NgModule({
    declarations: [HelloWorldComponent, PrivateComponent],
    exports: [HelloWorldComponent]
})
class HelloWorldAppModule {
}

As you can see, this module exports only HelloWorldComponent , however, inside the template of HelloWorldComponent the PrivateComponent is used. This should work fine, since both components are registered in declarations .

Then, I create another module UsesHelloWorldModule that imports HelloWorldAppModule and so, as I understand, I can use components exported by it in templates of directives registered within HelloWorldAppModule . So here it is:

@Component({
    selector: 'uses-hello-world',
    template: `<hello-world></hello-world><private></private>`
})
class UsesHelloWorldComponent {
}

@NgModule({
    imports: [HelloWorldAppModule],
    declarations: [UsesHelloWorldComponent],
})
class UsesHelloWorldModule {
}

However, I also used <private> component from the HelloWorldAppModule that was not exported. So what's going to happen? Am I right that angular is going to throw an error when parsing the <private></private> tag?

EDIT:

Also, what will happen if only is used inside UsesHelloWorldComponent :

@Component({
    selector: 'uses-hello-world',
    template: `<hello-world></hello-world>`
})
class UsesHelloWorldComponent {
}

Please note that it uses <private> inside its template.

Appreciate any comments as there is not much examples of private components on the web.

<private></private> should cause an error about missing CUSTOM_ELEMENTS_SCHEMA . If you proveded CUSTOM_ELEMENTS_SCHEMA to be able to use custom tags that are not Angular components, then you won't get an error, unless you also add bindings like <private [prop]="value"> - which will cause an error because <private> won't have a prop property when it's not a PrivateComponent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM