A6 — Angular Series : Angular Component Communication, CSS-Styling

Sourabhh Sethii
DXSYS
Published in
7 min readMay 22, 2020

DXSYS(Digital Experiences & Systems), welcome you all to the Sixth article of angular series. Let’s recap all the concepts we have gone so far.

A1.) Create A Project — You can check article on creating the project. Click Here.

A2.) Create A Component — You can check the article on creating a component . Click Here.

A3.) Manage-Events — You can check the article on managing basic events such as click. Click Here.

A4.) Handle Events, Share Services, Dependency-Injection — You can check the article on DI, Share Services. Click Here.

A5) Dependency Injection, Input, Output, Two-way-binding — You can go through the article on DI, Two Way Binding, Input and Output field decorator.Click Here.

We will look into below topics in detail

1.) Communication between Components

2.) Writing CSS Inside Components

3.) Apply CSS Conditionally With ngclass

4.) Use Global CSS Inside

Communication between Components

In Angular, components communication to each other to share data such as string, number, array, HTML or object. We need to understand relationship between components, first.

  1. ) Case First — when two components are not related to each other, they communicate through an Angular service.
Use Services — When Two Components are not related to each other.

2. ) Case Second — When you use a component inside another component, you create a component hierarchy. The component being used inside another component is known as the child component and the enclosing component is known as the parent component.

Use Input/Output Decorators — When there is parent child relationship between components

Parent and child components can communicate to each other in following ways:

• @Input()

• @Output()

• Temp Ref Variable

• ViewChild

• ContentChild

When components are not related to each other, they communicate using services. Otherwise, they communicate using one of the various options depending on the communication criteria.

@Input Decorator

You can pass data from a parent component to a child component using the @Input decorator. Data could be of any form such as the primitive type’s string, number, object, array, etc.To understand use of @Input, let’s create a component SampleFormComponent:

Use the SampleFormComponent component inside AppComponent.

AppComponent
<ul>  <app-sample-form-component *ngFor="let message of sharedservices.messageObject"  [message]="message.text" (update)="onUpdate(message.id, $event.text)" ></app-sample-form-component>
</ul>

AppComponent is using SampleFormComponent, so AppComponent is the parent component and SampleFormComponent is the child component. To pass data, the @Input decorator uses the child component properties. Here, we are passing [message] property to SampleFormComponent using @Input.

@OUTPUT

You can emit the event from the child component to the parent component using the @Output decorator.Angular is based on a one-directional data flow and does not have two-way data binding. So, we use @Output in a component to emit an event to another component. Let’s See SampleFormComponent in above example

@Output() update = new EventEmitter();

In template, onclick update is emitted which will further trigger the onUpdate function in AppComponet (Parent Component).

(click)="update.emit({text:message})"

DIRECTIVES

Directives create DOM elements and change their structure orbehavior in an Angular application. There are three types of directives in Angular:

1.) Components: Directives with templates.

2.) Attribute directives: Change appearance and behavior of an

element, component, or other directive.

3.) Structural directives: Change DOM layout by adding or

removing elements.

The basic difference between a component and a directive is that a component has a template, whereas an attribute or structural directive does not have a template. Angular has provided us many inbuilt structural and attribute directives. Inbuilt structural directives are *ngFor and *ngIf. Attribute directives are NgStyle and NgModel. We will look these in depth in our next article series on Deep Dive in Angular Directives Series.

Styling Basic Angular application

Let us now look into basic styling in angular. To understand how to style in angular , you have to understand how the DOM is set up. When we write an app-sample-form-component component, in the DOM you'll see app-sample-form-component and then nested inside of it you'll see a div and then inside of that div you'll see an input and a button.

Although you might be used to writing div inside of frameworks when you build a component to represent the outer element of that component, you actually don't need to do that because this input and button will be wrapped inside of this app-sample-form-component. We can add styles here, so we'll say styles. This is an array of strings available in metadata in @Component decorator. Then I can add a style to app-sample-form-component.

styles:[ margin-bottom: 10px; ]

When I do this, you won’t see anything change over here. There’s no margin-bottom applied to it. That's because our component doesn't have any display to find. Meaning that on our app-sample-form-component, which we can reference in here through :host, we need to define a display such as block or I'm going to choose flex.Once I choose a display for my component, the type of display I want it to have, now it can represent that margin-bottom and it will know how to apply it based on this display. I also want this input and the button to be on top of each other, so I'm going to choose flex-direction: column. Now these are on top of each other. you can see that inside of our component a :host will refer to our component, which in the DOM is represented by this app-sample-form-component. Outside of the component, app-sample-form-component can be selected by using the element selector of it or by giving it a class or any other traditional method of selecting it.

The other piece here I need to show is that if I want to select everything, every selector inside of my component and I wanted everything to have a font-family of monospace. In a traditional page this would select every element inside and outside of this component. It would select it across your entire app.

ngClass

While CSS has focus, active, and other things that would handle most of the Events on the dom, there are some more complex scenarios. We're going to handle those with ngClass, to conditionally apply Classes. The syntax for that is ngClass, wrapped into square brackets because we're going to evaluate the right side of this.

Remember if you don’t put the square brackets in, it just treats this as a string. We’re going to evaluate this side. We’re going to pass in an object, where the key is a name of a Class. We’re going to call this Class mouseclickedClass, and on mouseClick we're going to set the border: 3px solid yellow.

styles: [ `  :host{   
display : flex; flex-direction : column; } input:focus{ font-weight: bold; outline: none; } .mouseclickedClass{ border : 3px solid yellow; } button{ border: none;
} ` ]

In our ngClass, that the left-hand side or key of this is going to be called mousedown, because this Class relates to this. The right-hand side of this, so the value of this object, is going to be a true or false statement based on whether or not we want to apply this Class.

[ngClass] = “{mouseclickedClass:ismouseclicked}”

Global Styles

Global CSS and stylesheets are also available to Angular Components even though the styles you define inline will remain isolated to the Component itself. You can customize this behavior using ViewEncapsulation if you need to keep global styles out of your Components.

Angular components can be styled via global CSS the same as any other element in your application. Simply drop a `<link>` element on your page (typically in index.html) and you’re good to go! However, Angular additional gives developers more options for scoping your styles.

encapsulation: ViewEncapsulation.Emulated,  
selector: 'app-sample-form-component',

By default in Angular, when you attach CSS directly to a component, we scope that css exclusively to that component. This scoping isolates it from the rest of your application. This additional capability means that there are two ways to use CSS with Angular.

Modes of Component Encapsulation

1[Emulated Mode] Developers who use component-scoped CSS in Angular will default to emulated mode for this encapsulation. In emulated mode, we generate and attach random attributes to each instantiated component, and then create styles that use those generated attributes as selectors.

2[NativeMode] We also support Native mode, which will use Shadow DOM to create additional contexts and prevent cross-component leakage of styles. This will work in any browsers with support for Shadow DOM v1. Native mode creates a shadow root under each component, which will isolate the component completely, even from styles defined globally (global styles DOM pierce components with emulated view encapsulation).

3[None Mode] The third and last encapsulation you can choose is None, which means that all of your CSS ends up being globally applied. You can use this if you want to opt-out of Angular’s style encapsulation completely.

We will look styling in detail in Angular Styling Series.

Output Screen :

Code Repository will be available at below location :

Interview Questions

Question 1.) What is angular directives?

Question 2.) How Communication Happens between Components?

Question 3.) How to Style Angular application?

Question 4.) Different Modes of Angular Component Encapsulation?

--

--

Sourabhh Sethii
DXSYS
Editor for

I am an author of Building Digital Experience Platform and I am passionate about emerging technologies. https://sourabhhsethii.com/