What is the advantage of using model class in angular?

We cant directly create an object in the respective component and work on it right .But why we are creating the object in seperate file?

Since angular is typically used with typescript, you can use that class for type checking (in many cases you might also use an interface instead); e.g.

class LoginComponent {
  private user: User;
  // ...
}

Generally speaking though, a model class also allows you adding custom accessors and methods, as well as properties that are added automatically during instantiation; for example

class Person {
  constructor (firstname, lastname) {
    this.firstname = firstname
    this.lastname = lastname
    this.created = Date.now()
  }

  get fullname () {
    return `${this.firstname} ${this.lastname}`
  }

  toString () {
    return this.fullname
  }
}

So without that class (or an equivalent factory function), you’d have to take care of all this manually wherever you are using such an object in your application.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.