标签: angular2-forms

如何在没有ng-model的情况下以角度2形式以编程方式更改原始属性

我是Angular 2框架的新手.我感谢任何帮助.

我在角2中有通常的组件:

import {FORM_DIRECTIVES, FormBuilder, Validators} from 'angular2/common';

export class TestComponent {
    public values = ['value1', 'value2', 'value3', 'value4'];
}
Run Code Online (Sandbox Code Playgroud)

然后我注入FormBuilder构造函数:

@Inject(FormBuilder) public fb
Run Code Online (Sandbox Code Playgroud)

HTML包含下一个标记:

<input [(ngModel)]="formData.title" type="text" class="form-control" ngControl="title">
Run Code Online (Sandbox Code Playgroud)

标题和描述非常有用.但我添加了bootstrap下拉列表,它没有任何表单元素.

<div *ngFor="#value of values" (click)="onValueChanged(value)" class="dropdown-item">{{value}}</div>
Run Code Online (Sandbox Code Playgroud)

所以,问题是html标记不包含任何模型.我试图解决这个问题的方法是创建函数onValueChanged

 onValueChanged(value){
    this.formData.controls.value.updateValue(value);
    this.formData.value = value;
    console.log(this.formData.pristine) //Still true :(
}
Run Code Online (Sandbox Code Playgroud)

这两行都不起作用,因为this.formData.pristine下拉列表更改后没有更改.

现在我正在考虑如何更新FormBuilder,例如,有一些方法可以this.fb.update()

javascript angular2-forms angular2-formbuilder angular

4
推荐指数
1
解决办法
5737
查看次数

angular2表单验证:获取ngForm的实例

如何在组件中引用"myform"?可能吗?必须使用formbuilder(我试图避免使用它)?

<form #myForm="ngForm">
    <label class="col-sm-12" [class.ng-invalid]="!(value.valid || Value.pristine)">Value</label>
    <input type="text"  required ngControl="value" #value="ngForm" class="form-control text-center" [(ngModel)]="value" />
  </form>
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular

4
推荐指数
1
解决办法
3222
查看次数

Angular 2表单,包含对象输入数组

我正在构建一个开发票应用程序来学习Angular2.我遇到的问题是如何构建行项目组件,其中一行包含3个应该来自的输入并绑定到行项目数组中的对象.

在角度1中,我可以通过向ng-form输入的容器添加指令来轻松实现此目的.这里的等价物是什么?

这是我的代码:

HTML:

<form name="form" ng-submit="$ctrl.submit(form)" novalidate>

<!-- some more code -->

<ul class="list invoice-table__body">
  <li *ngFor="let item of model.lineItems; let i = index">
    <input
      type="text"
      name="description"
      class="col-sm-8"
      [(ngModel)]="item.description">

    <input
      type="number"
      name="quantity"
      class="col-sm-2"
      [(ngModel)]="item.quantity">

    <input
      type="number"
      name="total"
      class="col-sm-2"
      [(ngModel)]="item.total">
  </li>
</ul>

<!-- some more code -->

</form>
Run Code Online (Sandbox Code Playgroud)

零件:

import { Component } from '@angular/core';
import { Invoice } from './invoice.model';
import { InvoiceLineItems } from './invoice-line-item.model';

@Component({
  selector: 'create-invoice',
  templateUrl: 'create-invoice/create-invoice.html'
})
export class CreateInvoiceComponent {
  model: …
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular

4
推荐指数
1
解决办法
1万
查看次数

使用Angular 2和Spring MVC中的其他表单字段上传文件

我正在尝试将文件和其他表单字段内容从我的Angular 2前端上传到Spring后端.但不知怎的,我无法做到.这是我的代码:

app.component.ts

fileChange(e){
    this.fileList = e.target.files;
  }

uploadPdf(){
    if(this.fileList.length>0){
      let file: File = this.fileList[0];
      let formData:FormData = new FormData();

      formData.append('uploadFile', file, file.name);
      formData.append('info',this.model);

      console.log(file.size);

      let headers = new Headers();
      headers.append('Accept', 'application/json');
      let options = new RequestOptions({ headers: headers });
      this.http.post(this.url,formData, options)
        /*.map((res: Response) => res.json())*/
        .catch(error => Observable.throw(error))
        .subscribe(
          data =>{
            this.data = data;
            console.log(this.data);
          }
          ,
          error => console.log(error)
        )
    }
  }
Run Code Online (Sandbox Code Playgroud)

app.cmoponent.html

<h1 class="text-center">
  PDF Viewer and Uploader Example
</h1>
<div class="text-center">
  <form …
Run Code Online (Sandbox Code Playgroud)

file-upload spring-mvc angular2-forms angular

4
推荐指数
1
解决办法
5765
查看次数

angular2 formBuilder组异步验证

我正在尝试实现异步验证器但没有成功......

我的组件创建了一个表单:

this.personForm = this._frmBldr.group({
  lastname:  [ '', Validators.compose([Validators.required, Validators.minLength(2) ]) ],
  firstname: [ '', Validators.compose([Validators.required, Validators.minLength(2) ]) ],
  birthdate: [ '', Validators.compose([ Validators.required, DateValidators.checkIsNotInTheFuture ]) ],
  driverLicenceDate: [ '', Validators.compose([ Validators.required, DateValidators.checkIsNotInTheFuture ]), this.asyncValidationLicenceDate.bind(this) ],
}, {
  asyncValidator: this.validateBusiness.bind(this),
  validator: this.validateDriverLicenseOlderThanBirthdate,
});
Run Code Online (Sandbox Code Playgroud)

我的验证方法

validateBusiness(group: FormGroup) {
  console.log('validateBusiness')
  return this._frmService
    .validateForm(group.value)
    .map((validationResponse: IValidationResponse) => {
      if (validationResponse) {
        validationResponse.validations.forEach( (validationError: IValidationErrorDescription) => {
                        let errorMsg = validationError.display;
                        let errorCode = validationError.code;
                        validationError.fields.forEach( (fieldName: string) => {
                            console.log(fieldName);
                            let control = …
Run Code Online (Sandbox Code Playgroud)

validation angular2-forms angular2-formbuilder angular

4
推荐指数
1
解决办法
5100
查看次数

处理复选框Angular2上的更改

我有复选框,我想要使用(change)它.默认为"已选中",但点击后我想要清除输入文本"激活密钥".重新检查后,我想生成guid并再次添加到输入.如果选中或不选中复选框怎么办?

<div class="checkbox">
    <label>
       <input type="checkbox" checked (change)="handleChange($event)" > 
           Generate key
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

TS

handleChange(e) {
    var isChecked = e.isChecked;
    if (isChecked) {
        this.gatewayForm.patchValue({ 'activationKey': this.guid() });
    }
    else {
       this.gatewayForm.controls['activationKey']
           .setValue('', { onlySelf: true });
    }
}
Run Code Online (Sandbox Code Playgroud)

checkbox angular2-forms angular

4
推荐指数
1
解决办法
6197
查看次数

Angular2如何使用默认值设置单选按钮

我是Angular2的新手,我有一个无线电组,我正在尝试使用[(ngModel)]将它绑定到实体person.testBoolean,以便我可以将它保存在数据库中.我想设置一个默认值为选中,我看到几个例子,发现他们将默认值设置为[(ngModel)],但在我的情况下,我想将它绑定到我的实体,因此我不能使用[(ngModel)] .任何人都可以建议其他选择.checked = idx不起作用.

<div class="form-group">
    <label for="radioboolean">Boolean: </label>
    <div *ngFor="let entry of entries; let idx = index" class="radio-inline" >
       <input type="radio" [(ngModel)]="person.testBoolean" name="radiogroup" [checked]="idx === 1" [value]="entry.id" />{{ entry.description }}
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Ts码:

 entries = [
              {id: 1, description: 'True' },
              {id: 2,description: 'False'},
              {id: 3,description: 'Undefined'}
           ];
Run Code Online (Sandbox Code Playgroud)

人是我的实体:

export interface IPerson {

    id: string;
    name: string;
    testNumber: number | null;
    testDatetime: Date | null;
    testBoolean: boolean | null;
    // Refs to parent entities
    team: ITeam;
    teamId: string;

};
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular

4
推荐指数
1
解决办法
1万
查看次数

在Angular 5中使用文件上传保存FormData

我正在尝试将文件与FormData一起保存在Angular 5中。我可以获取单个文件,但是不知道如何获取所有文件。我有三个图像文件和输入字段,尝试搜索示例。但是只能上传多个文件。我想从此表单上载每个文件。

下面是我的代码:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Category } from '../../../shared/services/categories/category';
import { CategoriesService } from '../../../shared/services/categories/categories.service';

@Component({
  selector: 'app-add-category',
  templateUrl: './add-category.component.html',
  styleUrls: ['./add-category.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AddCategoryComponent implements OnInit {
  
  category: Category = new Category();
  fileToUpload: File = null;
  
  constructor(
    private categoriesService: CategoriesService,
    private route: ActivatedRoute,
    private location: Location  
  ) { }

  ngOnInit() {
  }

  goBack(): void {
    this.location.back(); …
Run Code Online (Sandbox Code Playgroud)

file-upload angular2-forms angular angular5

4
推荐指数
3
解决办法
3万
查看次数

Angular2:在FormArray的索引1处找不到表单控件

在运行时,我从JSON对象获取所有记录,并在表单控件中获取值.但是,在表单数组中,我只获得了许多记录中的第一个.

控制台中显示的错误:

在FormArray._throwIfControlMissing中找不到索引1处的表单控件

JSON对象和错误的图像:

在此输入图像描述

  1. 接口

export interface IService {
    ServiceID: number,
    Name: string,
    Staffs: IStaffView[]
}

export interface IStaffView {
    StaffServiceID: number,
    StaffID: number,
    Name: string
}
Run Code Online (Sandbox Code Playgroud)

  1. 零件

import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Observable } from 'rxjs/Rx';
import { FormBuilder, FormGroup, FormControl, FormArray , Validators } from '@angular/forms';

import { RESTService } from '../../Service/REST.service';
import { IService, IStaffView } from '../../Model/service.model';
import { …
Run Code Online (Sandbox Code Playgroud)

typescript angular2-forms angular formarray

4
推荐指数
1
解决办法
5212
查看次数

自定义控件中的setValidators,无需Angular中的引用

我创建了一个自定义输入控件。我不想创建任何自定义验证。我想使用默认必需的minLength,maxLength等。我知道我可以这样做

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);
Run Code Online (Sandbox Code Playgroud)

但是我无法从父组件发送表单引用。我如何在文本框组件内使用setValidator。

// input-box.component.ts    
    import { Component, Input, forwardRef } from '@angular/core';
    import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';


    @Component({
      selector: 'app-input-box',
      template:`<label >{{inputdata.label}}</label><br>
      <input type="text" required #textBox [value]="textValue" (keyup)="onChange($event.target.value)" />`,
      styleUrls: ['./input-box.component.less'],
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() => InputBoxComponent),
          multi: true
        },
        /*{
          provide: NG_VALIDATORS,
          useExisting: forwardRef(() => InputBoxComponent),
          multi: true,
        }*/]
    })
    export class InputBoxComponent implements ControlValueAccessor {
      @Input() inputdata: any;
      private textValue: any = '';

      onChange(value) {
        this.textValue = value;
        this.propagrateChange(value);
      }

      private …
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular-validation angular angular4-forms angular5

4
推荐指数
1
解决办法
2309
查看次数