Câu hỏi phỏng vấn Angular
Câu hỏi

What is the difference between @Component and @Directive in Angular?

Câu trả lời

In Angular, @Component and @Directive are both decorators used to define classes that extend the functionality of HTML elements in an Angular application. However, they serve distinct purposes and are used in different scenarios.

@Component

@Component is used to define a component, which is essentially a directive with a template. This means it not only contains application logic but also has an associated view defined by HTML templates. Components are the primary building blocks of Angular applications, used to create reusable UI elements that encapsulate functionality including the view, data bindings, and behavior.

Key characteristics of @Component include:

  • Template Requirement: Components must have a template, which can be defined inline or linked via a URL.
  • Shadow DOM: Components can create a new view, known as the Shadow DOM, where the template is rendered.
  • Encapsulation: They encapsulate the functionality, focusing on how things look and behave on the UI.
  • Usage: Used to break up the application into smaller, manageable, and reusable components.

An example of a component might look like this:

typescript Copy
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  title = 'Hello World';
}

@Directive

@Directive, on the other hand, is used to add behavior to existing DOM elements or existing components. It does not involve a template of its own, making it suitable for adding functionalities such as changing appearance, responding to user interactions, or manipulating the DOM.

Key characteristics of `@Dire...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What are the ways to control AOT compilation?

senior

What is Incremental DOM? How is it different from Virtual DOM?

middle

When would you use eager module loading?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào