Difference between using ng model and ng control in angular2?

 <form role="form" #form="form" (ng-submit)="submit(form.value)">
    <input type="text" placeholder="Enter your name" ng-control="name">
    <input type="text" placeholder="Enter your email" [(ng-model)]="email">
    <button>Submit</button>
  </form>

What is diff b / w using ng-model and ng-control? When to use each of them?

+4
source share
2 answers

The controls are responsible for receiving prompts about the state of the form or specific input (valid, virgin, touched, ...). It is usually used to display validation errors, if any. Here is an example:

<div
     [ngClass]="{'has-error':!inputControl.valid && !state.control.pending,'form-group':label,'form-group-sm':label}">
  <label *ngIf="label" for="for"
     class="col-sm-2 col-md-2 control-label">My input</label>

  <div class="col-sm-8 col-md-8"
       [ngClass]="{'col-sm-8': label, 'col-md-8': label}">
    <input [(ngModel)]="myInput" [ngFormControl]="inputControl"/>
    <span *ngIf="!inputControl.valid" class="help-block text-danger">
      <div *ngIf="state?.errors?.required">The field is required</div>
      (...)
      <div *ngIf="state?.errors?.invalidZip">The zip code format isn't correct</div>
    </span>
  </div>
</div>

You can also detect changes in the input using the valueChangescontrol attribute , as described below:

this.inputControl.valueChanges.subscribe(data => {
  console.log('value updated - new value = '+data);
});

Since this is observable, you can use statements to create an asynchronous processing chain. For example, to synchronize a list based on input:

inputControl.valueChanges.debounceTime(500).flatMap(
  val => {
    return this.service.searchPlaces(val);
  }).subscribe((data) => {
    this.places = data;
  });

, ngModel , . , , , .


@Günter, . :

<form role="form" #form="form" (ngSubmit)="submit(form.value)">
  <input type="text" placeholder="Enter your name" ngControl="name">
  <input type="text" placeholder="Enter your email" [(ngModel)]="email">
  <button>Submit</button>
</form>
0

ngControl, ngModel ngFormControl NgControlStatus, ...

NgControlStatus Angular, CSS (valid/invalid/dirty/etc).

ngFormControl , Control, .

NgFormControl DOM.

0

Source: https://habr.com/ru/post/1629314/


All Articles