如何访问动态添加的输入元素

时间:2018-06-23 15:12:22

标签: javascript angular typescript angular4-forms

我正在以反应形式动态添加输入元素Programming languaes,并且工作正常,但是我无法理解如何在模板或html视图中显示这些动态添加的programming languages元素。我已经尝试过,但是我认为它是完全错误的,我无法理解如何纠正它或我犯了什么错误。

我的组件代码是:

import { Component, OnInit } from '@angular/core';
import { NgForm, FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';
import { ProgLang } from '../shared/progLang.model';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})

export class SignupComponent implements OnInit{
  userGroup: FormGroup;
  contact = [];
  languages = [
    new ProgLang(1, 'PHP'),
    new ProgLang(2, 'Javascript'),
    new ProgLang(3, 'C#'),
    new ProgLang(4, 'Others')
  ];

  constructor(private fb:FormBuilder) {

  }

  ngOnInit() {
      this.createForm();
  }

  createForm() {

    this.userGroup = this.fb.group({
      'name': [null, Validators.compose(
        [
          Validators.required, 
          Validators.pattern("^[a-zA-Z]*$")
        ]
      )],
      'email': [null, Validators.compose(
        [
          Validators.required, 
          Validators.email
        ]
      )],
      'age': [null, Validators.compose(
        [
          Validators.required, 
          Validators.pattern("^[0-9]*$"), 
          Validators.min(18)
        ]
      )],
      'address': this.fb.group({
        'address_1': [null,Validators.required],
        'address_2': null,
        'city': [null, Validators.required]
      }),
      'prog_langs': this.fb.array([]),
      'contacts': this.fb.array([this.initContact()])
    });

    this.initProgLang();
  }

  initProgLang() {
    const contr = <FormArray>this.userGroup.controls['prog_langs'];

    for(let el of this.languages) {
      let group = this.fb.group({});
      let checkBoxControl = this.fb.control('');

      group.addControl(el.name, checkBoxControl);
      //add to form array
      contr.push(group);
    }

  }

  initContact() {
        return this.fb.group({
            contact_name: ['', 
            Validators.compose(
              [
                Validators.required,
                Validators.pattern("^[a-zA-Z]*$")
              ]
            )],
            contact_number: ['', [Validators.required, Validators.pattern("^[0-9]{10}$")]]
        });
  }

  addContact() {
        const control = <FormArray>this.userGroup.controls['contacts'];
        const addrCtrl = this.initContact();
        control.push(addrCtrl);
    }
}

我的ProgLang模型如下:

export class ProgLang {
  public id: number;
  public name: string;

  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}

我的观点如下:

<div>
  <h4>Signup</h4>
  <div>
    <form 
    [formGroup]="userGroup"
    #f="ngForm">
      <div class="form-group">
        <label for="name">Name</label>: 
        <input type="text" formControlName="name" placeholder="Enter Name"/>
        <span *ngIf="userGroup.get('name').touched && userGroup.get('name').status == 'INVALID'">
          <span *ngIf="userGroup.hasError('required','name')">Please enter name</span>
          <span *ngIf="userGroup.hasError('pattern','name')">Invalid name</span>

        </span>
      </div>

      <div class="form-group">
        <label for="email">Email</label>: 
        <input type="text" formControlName="email" placeholder="Enter Email"/>
        <span *ngIf="userGroup.get('email').touched && userGroup.get('email').status == 'INVALID'">
          <span *ngIf="userGroup.hasError('required','email')">Please enter email</span>
          <span *ngIf="userGroup.hasError('email','email')">Invalid email</span>
         </span>
      </div>

      <div class="form-group">
        <label for="age">Age</label>: 
        <input type="text" formControlName="age" placeholder="Enter Age"/>
        <span *ngIf="userGroup.get('age').touched && userGroup.get('age').status == 'INVALID'">
          <span *ngIf="userGroup.hasError('required','age')">Please enter age</span>
          <span *ngIf="userGroup.hasError('pattern','age')">Invalid age</span>
          <span *ngIf="userGroup.hasError('min','age')">Min age should be 18 years</span>

        </span>
      </div>

      <div formGroupName="address">  
        <h4>Adddress</h4> 
        <div class="form-group">
        <label for="address_1">Address 1</label>: 
        <input type="text" formControlName="address_1" placeholder="Enter Address 1"/>
        <span *ngIf="userGroup.get('address.address_1').touched && userGroup.get('address.address_1').status == 'INVALID'">
          <span *ngIf="userGroup.hasError('required','address.address_1')">Please enter address line 1</span>

        </span>
        </div>

        <div class="form-group">
        <label for="address_2">Address 2</label>: 
        <input type="text" formControlName="address_2" placeholder="Enter Address 2"/>
        </div>

        <div class="form-group">
        <label for="city">City</label>: 
        <input type="text" formControlName="city" placeholder="Enter City"/>
        <span *ngIf="userGroup.get('address.city').touched && userGroup.get('address.city').status == 'INVALID'">
          <span *ngIf="userGroup.hasError('required','address.city')">Please enter city</span>

        </span>
        </div>
      </div>

      <div class="form-group">
        <label>Your favorite programming language: </label>

        <div class="form-group" formArrayName="prog_langs">
          <div *ngFor="let lngs of userGroup.controls.prog_langs.controls let i=index" [formGroupName]="i">
            <div class="form-group">
              <label>{{ lngs.controls }}</label>:
              <input type="text" formControlName="lngs.name" class="txt_contact" placeholder="Enter Name"/>
            </div>
          </div>
        </div>
      </div>

      <div class="form-group" formArrayName="contacts">
        <label for="contacts">Contact</label>: <span><button (click)="addContact()">Add Contact</button></span>
        <div *ngFor="let cont of userGroup.controls.contacts.controls let i=index" [formGroupName]="i">
          <div class="form-group">
            <label for="contact_name" class="lbl_contact">Name</label>:
            <input type="text" formControlName="contact_name" class="txt_contact" placeholder="Enter Name"/>
            <label for="contact_number" class="lbl_contact">Number</label>:
            <input type="text" formControlName="contact_number" class="txt_contact" placeholder="Enter Number"/>

            <span *ngIf="userGroup.controls.contacts.controls[i].controls.contact_name.touched && userGroup.controls.contacts.controls[i].controls.contact_name.status == 'INVALID'">
              <span *ngIf="userGroup.controls.contacts.controls[i].controls.contact_name.errors.required">Please enter name</span>
              <span *ngIf="userGroup.controls.contacts.controls[i].controls.contact_name.errors.pattern">Invalid name</span>
            </span>

            <span *ngIf="userGroup.controls.contacts.controls[i].controls.contact_number.touched && userGroup.controls.contacts.controls[i].controls.contact_number.status == 'INVALID'">
              <span *ngIf="userGroup.controls.contacts.controls[i].controls.contact_number.errors.required">Please enter number</span>
              <span *ngIf="userGroup.controls.contacts.controls[i].controls.contact_number.errors.pattern">Invalid number</span>
            </span>


          </div>
        </div>
      </div>

      <div class="form-group">
        <button type="submit" [disabled]="!f.valid" class="btn btn-primary">Sign Up</button>
      </div>

    </form>

  </div>
</div>

0 个答案:

没有答案