Middle+
Explain the architectural patterns MVC and MVVM. How are they implemented in Angular?
sobes.tech AI
Answer from AI
MVC (Model-View-Controller) and MVVM (Model-View-ViewModel) are architectural patterns that separate the responsibilities of application components to improve support and scalability.
-
MVC divides the application into:
- Model — data and business logic.
- View — user interface.
- Controller — intermediary that handles user input, updates the model, and selects the view.
-
MVVM differs in that it adds a ViewModel layer, which binds the View and Model through two-way data binding:
- Model — data and business logic.
- View — UI.
- ViewModel — an abstraction of the View, containing presentation logic and state, providing two-way binding with the View.
In Angular, a pattern close to MVVM is implemented:
- Component (ViewModel) — contains logic and state, binds to the template.
- Template (View) — HTML with bindings to component properties and events.
- Service (Model) — business logic and data, injected into components.
Angular uses two-way data binding (for example, with [(ngModel)]), which simplifies synchronization of state between the View and ViewModel.
Example:
@Component({
selector: 'app-user',
template: `
<input [(ngModel)]="userName" />
<p>Hello, {{ userName }}!</p>
`
})
export class UserComponent {
userName = '';
}
Here, UserComponent is the ViewModel, the template is the View, and the data userName is automatically synchronized between them.