Skip to main content

Model vs InterFace vs Class

1. Class

=> It is look like blue print of object

 class Employee {
      empName: string;
      joinDate: string;

      constructor(empName = '',joinDate = '') {  
          this.empName = empName;
          this.joinDate = joinDate;
          }
  }

2. InterFace 

• Interfaces only define the shape of an object.

• They cannot have methods with implementations.

• They are removed at runtime (no compiled JavaScript code).

  export interface IUser {
    name: string;
    email: string;
  }

3. Model

• A model is typically a TypeScript class used for representing data from APIs or databases.

• It often includes methods to manipulate data

   createModel() {
    let models = {
      "empName": this.empForm.value.empName == null || this.empForm.value.empName == undefined ? '' : this.empForm.value.empName,
      "joindate": (this.empForm.value.joinDate == null || this.empForm.value.joinDate == "" || this.empForm.value.joinDate == "Invalid Date") ? '0001-01-01' : moment(this.empForm.value.joinDate).format('YYYY-MM-DD'),            
 }
    return models;
  }

  Now we can directly use to send api data

  async onsubmit() {
    let model = await this.createModel();
    this.myService.Create(model, 'employeedetails', 'empid',  1,'', '1').subscribe(res => {
      alert(res.status);
    })
}


More details
-------------
In Angular (and in general programming), models play an important role in
organizing and managing data efficiently. They act as a blueprint for yourdata and ensure consistency and structure throughout your application.
Here’s why using models is important, especially in Angular development:

export class ModelUseReativeFormComponent implements OnInit {
  userForm!:FormGroup;
  data:any;
  userModel={
    name:"John",
    job:'Developer'
  }
  constructor(private fb: FormBuilder){ }
  ngOnInit(): void {
    this.user();
    this.populateFormData();
  }
  user(){
   this.userForm = this.fb.group({
    name:'',
    job:''
    })
  }
  // populateFormData(){
  //   this.userForm.get('name')?.setValue(this.userModel.name);
  //   this.userForm.get('job')?.setValue(this.userModel.job);
  // }

    // Populate the form data with the values from userModel
    populateFormData() {
      this.userForm.patchValue({
        name: this.userModel.name,
        job: this.userModel.job
      });
    }
  onSubmit(){
    this.data = this.userForm.value;
  }
}




Comments

© 2020 The JavaDS Hub

Designed by Open Themes & Nahuatl.mx.