Реактивные формы Ангуляр Реактивные формы Ангуляр angular reactive form

Реактивные формы Ангуляр

Open in new window

Реактивные формы.

import { ReactiveFormsModule } from '@angular/forms';

Контролы

export class NameEditorComponent {
  name = new FormControl('');
}


<input type="text" [formControl]="name">


 updateName() {
  this.name.setValue('Nancy');
}

Группировка контролов.

import { FormGroup, FormControl } from '@angular/forms';


export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
  });


<form [formGroup]="profileForm">

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label>

  <label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label>

</form>

Проверка из шаблона.

<button type="submit" [disabled]="!profileForm.valid">Submit</button>

Вложенная форма.

export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl(''),
      zip: new FormControl('')
    })
  });
}

Шаблон.

<div formGroupName="address">
  <h3>Address</h3>

  <label>
    Street:
    <input type="text" formControlName="street">
  </label>

  <label>
    City:
    <input type="text" formControlName="city">
  </label>

  <label>
    State:
    <input type="text" formControlName="state">
  </label>

  <label>
    Zip Code:
    <input type="text" formControlName="zip">
  </label>
</div>

FormBuilder

import { FormBuilder } from '@angular/forms';

constructor(private fb: FormBuilder) { }



export class ProfileEditorComponent {
  profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
  });

Создаем форму для компаний.

    ....
    <div class="form-group row">
        <div class="col-md-2">
            <label class="col-form-label">БИН</label>
        </div>
        <div class="col-md-4">
            <input formControlName="bin" type="text" class="form-control form-control-sm" required >
        </div>
        <div class="col-md-2">
            <label class="col-form-label">Город</label>
        </div>
        <div class="col-md-4">
            <select class="form-control" formControlName="city">
                <option *ngFor="let m of cities" [value]="m.id">{{m.name_ru}}</option>
            </select>
        </div>
      </div>
      ....

Компонент.

   ....

  companyForm = new FormGroup({
    name_ru: new FormControl('ru'),
    name_kz: new FormControl('kz'),
    bin: new FormControl('bin'),
    city: new FormControl(),
  })


  constructor(private form_service: FormCompanyService) { }

  ngOnInit() {
    this.form_service.getCities().subscribe((data: any) => {
      this.cities = data;
    });
  }


   ....

Сервис.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { API_URL } from '../../global';

@Injectable({
  providedIn: 'root'
})
export class FormCompanyService {

  constructor(private http: HttpClient) { }

  getCities(){
    return this.http.get(API_URL + `api/cities/`);
  }

}

Для сохранения внешнего ключа в сериализаторе джанго определим поле для записи.

class CompanySerializer(serializers.ModelSerializer):
    ...
    city_id = serializers.IntegerField(write_only=True)

Код компонента формы.

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Company } from '../model';
import { FormControl, FormGroup } from '@angular/forms';
import { FormCompanyService } from './service';
import { CompanyService } from '../company.service';


@Component({
  selector: 'app-company-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.sass']
})
export class FormComponent implements OnInit {

  @Input() item: Company;
  @Output() showList = new EventEmitter<boolean>();

  cities = [];

  companyForm = new FormGroup({
    name_ru: new FormControl(),
    name_kz: new FormControl(),
    bin: new FormControl(),
    city_id: new FormControl(),
  })


  constructor(private form_service: FormCompanyService, private company_service: CompanyService) { }

  ngOnInit() {
    this.form_service.getCities().subscribe((data: any) => {
      this.cities = data;
    });
  }

  list(){
    this.item = null;
    this.showList.emit(true);
    this.company_service.updateListEvent();
  }

  onSubmit(){
    this.form_service.newCompany(this.companyForm.value).subscribe((data) => {
      this.companyForm.reset();
      this.list();
    }, () => { alert('Error!!!') });
  }
}

Валидация.

import { Validators } from '@angular/forms';

...

name_ru: new FormControl('',Validators.required),

Other topics