We use property binding to pass value from component to form element in html and event binding to pass value from html to angular component.

  1. In the below code when we use [value] to get the value from component to html
  2. The same way we use (input) to get back value on event like change of name text
  3. {{employee.Name}} is used to display the value. You can remove [value] or (input) to check the behavior.
  4. Instead of this we can use ngModule by importing FormsModule which takes care of both propery and data binding

empform.html

<form>
<input type="text" [value]="employee.Name" (input)="employee.Name=$event.target.value" />
{{employee.Name}}
</form>

EmployeeModel.ts

export class Employee {
  private _Name: String;

  constructor(name: String) {
    this._Name = name;
  }
}

EmployeeController.ts

export class AddemployeeComponent implements OnInit {
.
.
  public employee: Employee;

  constructor() {
    this.employee = new Employee('Mugilvannan');
  }
.
.
}

  1. For NgModeul to work name attribute(i.e. employeeName) is mandatory in form field.
    Otherwise the value wont be reflected on change
  2. [ngModel] is for value binding and (ngModelChange) is for event binding. Both can be grouped in to format called banana-in-a-box. [(ngModel)]
  3. For using ngModel, FormsModule should be added to app.module.ts
  4. So when to use expanded syntax of ngModel. There would be times where you want to change the text into uppercase or lowercase once it is entered into textbox or formfields. In suchcase we should call an event which does it. At that time you would use (ngModelChange) instead of [(ngModel)].

addemployee.component.html

  <form>
    <table style="border-collapse:collapse;" border="1" cellpadding="5">
      <tbody>
        <tr>
          <td>Name</td>
          <td><input type="text" name="employeeName" [ngModel]="employee.Name" (ngModelChange)="employee.Name=$event" /></td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" value="Add Employee" (click)="employee.Name='test'" />
          </td>
        </tr>
      </tbody>
    </table>
  </form>
  {{employee.Name}}

addemployee.component.html – Banana-in-a-Box format

.
.
<td><input type="text" name="employeeName" [(ngModel)]="employee.Name"/></td>
.
.

Comments are closed.