🎨 Angular Components in Depth β€” Building Your First UI

1. Quick Recap

  • Now we’re diving into the heart of Angular β€” Components.

2. What is a Component?

  • Definition: Components are the building blocks of Angular applications.

  • They consist of:

    • TypeScript class β†’ logic & data

    • HTML template β†’ structure & layout

    • CSS/SCSS β†’ styles

Example:

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent {
  title = 'Hello Angular!';
}

3. Creating a New Component

Using Angular CLI:

ng generate component hello
# or short form
ng g c hello

This creates:

hello/
  hello.component.ts
  hello.component.html
  hello.component.css
  hello.component.spec.ts

4. Component Decorator Explained

  • selector β†’ custom HTML tag to use the component.

  • templateUrl β†’ path to HTML template.

  • styleUrls β†’ styles for this component only.


5. Using the Component in the App

  • Add the selector inside app.component.html:
<app-hello></app-hello>
  • Save β†’ see the new component in action.

6. Passing Data with @Input()

Example:

@Input() name = '';
<p>Hello, {{ name }}!</p>

Usage:

<app-hello name="Shubham"></app-hello>

7. Sending Events with @Output()

Example:

@Output() clicked = new EventEmitter<string>();

sendEvent() {
  this.clicked.emit('Hello from child!');
}
<button (click)="sendEvent()">Click Me</button>

8. Styling Components

  • Component styles are scoped by default in Angular.

  • You can use .css or .scss.


9. Best Practices for Components

βœ… Keep them small and focused.
βœ… Use meaningful selector names.
βœ… Reuse instead of duplicating UI.


10. Conclusion

  • Angular Data Binding & Directives.
0
Subscribe to my newsletter

Read articles from Shubham Deshmukh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shubham Deshmukh
Shubham Deshmukh

My career objective is to be a competent individual who can contribute significantly to an organization's growth and also get valuable exposure, that would help me enhance my skill sets and provide me with opportunities to grow and further develop my talents as an individual. Also will offer me a work-life balance.