Content Child Subscription in Angular – #3

This Post is a continuation of  Component Projection in Angular. Please go through that post before reading this one. Thanks.

Scenario:

In the previous example, RememberMe Component is projected inside UserForm template from AppComponent. UserForm has no direct access to the RememberMe Component. AppComponent is the only component which binds UserForm Component and RememberMe Component. In this case, How UserForm can access the projected RememberMe Components value?

For example:

The UserForm template has a message (You will be logged in for 30 days) shown when the remember me check box is clicked. Both the components has no direct access. This is where ContentChild comes in handy.

app.component.html

In this app template, app-userform acts as a parent and three elements are projected inside, which are a div, a app-remember-me and a button. In this scenario, app-remember-me component acts as a child to app-userform. So to access app-remember-me from app-userform, we need to use ContentChild.

Code:

userform.component.html

In the above, I have a code to display a message (You’ll be logged in for 30 days), which is shown only if the showMessage is true.

userform.component.ts

In the above code, I have imported ContentChild and AfterContentInit. ContentChild to access the child component, AfterContentInit interface to trigger a method after a content (in this case, app-remember-me) is initialized. showMessage is a boolean variable with false as default value.

I’ll create a ContentChild variable rememberChild as of RememberMeComponent type. We can use rememberChild to access the checked value. Once the content is initialized, I’ll subscribe the checked value from RememberMeComponent and assign the emitted boolean value to the showMessage. So the idea is, If I check the remember me button, true value is emitted from RememberMeComponent which is assigned to showMessage variable and the Message is shown dynamically in the DOM.

Result:

You can get the code from my repository.

(Visited 1 times, 1 visits today)

Share your thoughts