- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有以下代码:
import { Component, OnInit, ElementRef } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
showSort: boolean = false;
form: FormGroup;
name: FormControl;
sortSelf: FormControl;
sortItem: FormArray;
locationItems: FormArray;
constructor(private _fb: FormBuilder, private _elementRef: ElementRef ) {
}
ngOnInit(): void {
this.sortItem = this._fb.array([this.initSort()]);
this.form = this._fb.group({
sortItem: this.sortItem
});
}
initSort() {
return this._fb.group({
locationPicture: new FormControl('', []),
locationItems: this._fb.array([
this.initSortItems()
])
})
}
initSortItems() {
return this._fb.group({
itemPicture: new FormControl('', [])
})
}
addSort() {
this.sortItem.push(this.initSort());
}
addSortLocationItem(i?: number, t?: number) {
const control: FormArray = <FormArray> this.sortItem.at(i).get('locationItems');
control.push(this.initSortItems());
}
showImage(event, level?: string, i?: number, t?: number){
let file = event.target.files[0];
if(level === 'locationPicture'){
(<FormArray>this.sortItem.at(i)).controls['locationPicture'].setValue(file, {onlySelf: true});
}else{
(<FormArray>this.sortItem.at(i).get('locationItems')).at(t).get('itemPicture').setValue(file, {onlySelf: true});
}
}
next(value, valid: boolean){
console.log(`this is value ${JSON.stringify(value, null, 4)}`);
}
}
标记:
<div class="col-md-8 col-md-offset-2">
<form class="" action="index.html" method="post" [formGroup]="form" (ngSubmit)="next(form.value, form.valid)">
<div class="form-group">
<div formArrayName="sortItem" class="">
<div class="top-buffer-small">
<a (click)="addSort()" style="cursor: default">
Add Sort Location +
</a>
</div>
<div *ngFor="let sortLocation of sortItem.controls; let i=index">
<div [formGroupName]="i" class="">
<div class="form-group">
<label>Location Picture</label>
<input type="file" formControlName="locationPicture" class="form-control locationPicture" accept="image/*" capture="camera" (change)="showImage($event, 'locationPicture', i, t)">
<!-- <input type="file" formControlName="locationPicture" (change)="showImage($event)" /> -->
<img src="" alt="" class="location-image" width="80" height="80">
<small class="form-text text-muted" [hidden]="sortItem.controls[i].controls.locationPicture.valid">
Picture is required
</small>
</div>
<div formArrayName="locationItems" class="col-md-10 col-md-offset-1">
<div class="row">
<a (click)="addSortLocationItem(i,t)" style="cursor: default">
Add Item +
</a>
</div>
<!-- <div class="from-group" *ngFor="let eachItem of form.controls.sortItem.controls[i].controls.locationItems.controls; let t=index"> -->
<div class="form-group" *ngFor="let eachItem of sortLocation.get('locationItems').controls; let t=index">
<div [formGroupName]="t">
<div class="form-group">
<label>Item Picture</label>
<input type="file" formControlName="itemPicture" class="form-control itemPicture" capture="camera" (change)="showImage($event, 'itemPicture', i, t)">
<img src="" alt="" class="item-image" width="80" height="80">
<small class="form-text text-muted" [hidden]="sortItem.controls[i].controls.locationItems.controls[t].controls.itemPicture.valid">
Picture is required
</small>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<div class="text-center">
<button type="submit" name="button" class="btn btn-primary" [disabled]="form.invalid">Submit</button>
</div>
</form>
</div>
我正在尝试通过更新表单控件值来更新 showImage 方法中的表单。但是,我无法使用图片更新表格。当我尝试将其上传到“locationPicture”和“itemPicture”时,出现以下错误:
Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
请对此提供任何帮助
最佳答案
我也遇到了这个问题,不过我们可以分别处理file
和其他表单域。
这是我的代码,我想发布一个 FormData 对象
到 Django REST API,这个 formData
包含字符串和图像,还有 user_name
和密码
。我创建了一个组件 - upload-image-form
Image
类(我自己定义的)// images.ts
export class Image {
constructor(
public id: number,
public created: string, // set by back end
public userId: number,
public fileUrl: string,
public owner: string,
public des?: string,
public localImage?: File,
) { }
}
// upload-image-form.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { NgForm } from '@angular/forms/forms';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { Image } from '../image';
import { User } from '../user';
import { ImageService } from '../image.service';
@Component({
selector: 'app-upload-image-form',
templateUrl: './upload-image-form.component.html',
styleUrls: ['./upload-image-form.component.css']
})
export class UploadImageFormComponent implements OnInit {
@Input() user: User; // this value comes from parent component user-detail's tempolate
private file: File;
private formData: FormData = new FormData();
private imageForm: FormGroup;
private submitted = false;
private imageUrl = 'http://192.168.201.211:8024/images/';
private password: string;
constructor(
private imageService: ImageService,
private fb: FormBuilder,
) { }
ngOnInit() {
console.log(this.user);
this.createFrom(this.user); // create form here, so we can get this.user's value
}
createFrom(user: User) {
// I didn't put file field in this form
this.imageForm = this.fb.group({
id: 1,
created: '20170825',
userId: user.id,
fileUrl: 'http://images.fineartamerica.com/images-medium-large-5/mt-shuksan-picture-lake-dennis-romano.jpg',
owner: user.username,
des: '',
pw: '',
})
console.log(user);
}
// https://stackoverflow.com/a/41465502/2803344
// get a file object from form input
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.file = files[0];
}
onSubmit() {
// deal with string fields and file separately
this.submitted = true;
console.log(this.file); // file is here, captured by onChange()
console.log(this.imageForm.value); // other fields are here, captured by formGroup
this.formData.append('localImage', this.file, this.file.name);
for (let item in this.imageForm.value) {
console.log(item)
if (item !== 'pw') {
this.formData.append(item, this.imageForm.value[item]);
}
else {
this.password = this.imageForm.value[item];
}
}
// console.log('###here is the total form data');
console.log(this.formData);
console.log(this.formData.get('fileUrl'));
console.log(this.user.username);
this.imageService.post(this.formData, this.user.username, this.password)
.then(res =>{
console.log(res);
});
}
onClick(form: FormGroup) {
form.reset({
userId: this.user.id,
owner: this.user.username,
created: '20170825',
fileUrl: 'http://www.fujifilm.com.sg/Products/digital_cameras/x/fujifilm_x_t1/sample_images/img/index/ff_x_t1_001.JPG',
})
this.submitted=false;
console.log(form.value);
}
}
<!-- upload-image-form.component.html -->
<div [hidden]="submitted" *ngIf="user">
<h2>Upload New Image</h2>
<form [formGroup]="imageForm" (ngSubmit)="onSubmit()" >
<div class="form-group">
<label for="fileUrl">File Url</label>
<input type="url" class="form-control" id="fileUrl"
formControlName="fileUrl" required>
<div [hidden]="imageForm.get('fileUrl').valid || imageForm.get('fileUrl').pristine"
class="alert alert-danger">
File Url is required
</div>
<p>{{imageForm.get('fileUrl').valid | json}}</p>
<p>{{imageForm.get('fileUrl').value | json}}</p>
</div>
<!-- upload an image
don't define this field in formGroup-->
<div class="form-group">
<label for="localImage">Local File</label>
<input type="file" class="form-control" id="localImage"
(change)="onChange($event)" accept=".jpg, .png" >
</div>
<div class="form-group">
<label for="des">Description</label>
<input type="text" class="form-control" id="des"
formControlName="des">
</div>
<div class="form-group">
<label for="userId">User ID</label>
<input type="text" class="form-control" id="userId"
formControlName="userId" readonly>
<p>{{imageForm.get('userId').value | json}}</p>
</div>
<div class="form-group">
<label for="owner">Owner</label>
<input type="text" class="form-control" id="owner"
formControlName="owner" readonly>
</div>
<!-- input user's password -->
<div class="form-group">
<label for="pw">password</label>
<input type="password" class="form-control" id="pw"
formControlName="pw" required>
</div>
<button type="submit" class="btn btn-success" [disabled]="!imageForm.valid">Submit</button>
</form>
</div>
// image.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from "@angular/http";
import 'rxjs/add/operator/toPromise';
import { Image } from "./image";
import { User } from './user';
@Injectable()
export class ImageService {
private imageUrl = 'http://192.168.201.211:8024/images/';
//set headers for authorization, https://stackoverflow.com/a/34465070/2803344
createAuthorizationHeader(headers: Headers, name: string, pw: string) {
headers.append('Authorization', 'Basic ' +
btoa(`${name}:${pw}`));
}
createOptions(name: string, pw: string) {
let headers = new Headers();
this.createAuthorizationHeader(headers, name, pw);
// headers.append('Content-Type', 'application/json'); // without this
// headers.append('Content-Type', 'multipart/form-data'); // without this
let options = new RequestOptions({ headers: headers });
return options;
}
constructor(private http: Http) { }
getImageById(id: number): Promise<Image> {
const url = `${this.imageUrl}`;
console.log(url);
let headers = new Headers();
let token = 'token';
headers.append('X-Auth-Token', token);
return this.http.get(url, {headers: headers})
.toPromise()
// .then(res => res.json().data as Image)
.then(res => console.log(res))
.catch(this.handleError);
}
getImageByUrl(url: string): Promise<Image> {
return this.http.get(url)
.toPromise()
.then(res => res.json() as Image)
// .then(res => console.log(res))
.catch(this.handleError);
}
post(formData: FormData, user: string, pw: string): Promise<Image> {
let options = this.createOptions(user, pw);
console.log('we will have a post!');
console.log(formData.get('localImage'));
console.log(formData.get('fileUrl'));
console.log(formData.get('des'));
return this.http.post(this.imageUrl, formData, options)
.toPromise()
.then(res => res.json() as Image)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
你可以在github中找到整个项目,https://github.com/OnlyBelter/image-sharing-system2 .
关于forms - 更新一个 formControl,它是 Angular2 中 formArray 中的文件输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907471/
根据 the documentation , NLog 提供了一个 FormControl 目标,它将日志消息写入 Windows 窗体上控件的 Text 属性。但是,当我将 FormControl
以下是我的指令: restrict: 'E', scope: { }, templateUrl: 'directives/my.directive.html', link: function(scop
有没有办法在 Angular2+ 中声明表单模型时向 FormControl 添加任意元数据? 类似于: // In this fake example, {foo: 'bar'} is the me
如何在输入 FormControl 中显示一些不等于此 FormControl 值的文本? 例如,从服务器获取一些对象 - {id: 1, name: "Name1"} ,并设置 value Form
我正在研究 Angular Reactive 表单。这是我的组件类代码: ngOnInit(){ this.reviewForm = this.fb.group({
FormControl 在处理指令时遇到困难... 我正在尝试在我的输入字段中实现自动完成功能。我正在使用以下 Angular Material 指南,我逐字复制并粘贴了他们的 typescript
我正在使用 Angular 8 和 Reactive Forms。 在我的模板中,我有如下代码: 想法是,如果 validationError 为“truthy”,则在输入元素中添加红色边框。 无法
有没有办法检查是否需要控制? 当我实现一个专用的表单字段组件时出现了问题,该组件接受 FormControl 并且不仅有 输入 而且还有验证错误。由于某些字段是必需的,因此最好让用户知道 * 是否需要
FormControl 在处理指令时遇到困难... 我正在尝试在我的输入字段中实现自动完成功能。我正在使用以下 Angular Material 指南,我逐字复制并粘贴了他们的 typescript
我正在使用 Angular 8 和 Reactive Forms。 在我的模板中,我有如下代码: 想法是,如果 validationError 为“truthy”,则在输入元素中添加红色边框。 无法
我有一系列的项目。每个项目将通过使用 ng-repeat 和 ng-form 动态关联到一个表单。 ... 然后我就有可能创建新项目。但是当我这样做时,我希望他们的新形式变得变脏。 ADD
我想通过自定义指令将验证器动态添加到我的 FormControl。 @Directive({ selector: "[idNumber]", }) export class IdNumberD
我正在使用 Sematinc-UI 和 Angular2 ReactiveFormsModule 表单,我想使用 [formControl] 来选择多个。 如果我使用 select 它可以正常工作:
我现在已经根据一些逻辑从一个大型 FormGroup 中过滤掉了几个 FormControl - 我想知道如何合并/组合这些选定的 FormControl 并且只有一个订阅.. 我查看了 RxJS 文
我有 3 个字段与表单链接,类型为数字,当我修改字段 A 时,它会修改字段 B 和 C,当我修改字段 B 时,它会修改字段 A 和 C,当我修改字段 C 时,它会修改字段 A 和B相应地。 我的组件如
我有表单数组 FormGroup; let forms = [this.form1, this.form2]; 每个表单都有几个控件:FormControl。 如何向 FormControl 添加额外
我有一个使用自定义组件作为输入的表单,它接收一个 ControlName。当我在组件中键入内容时,它不会更新“错误”属性。 app-pf-input-text.ts: import { Compone
我讨论了表单应该如何与同事合作,我们对后端驱动的输入字段应该如何响应用户输入有不同的想法。 此讨论基于 Angular's definition of pristine "pristine" mean
我有包含 FormArray 的 FormGroup。由系统生成的 FormArray 中的每个 FormControls 如下所示: staffs: FormArray = { staffs
我使用的框架(Angular 7)。 我想像这样为 FormControl 设置一些类型。 startDate: FormControl; endDate: FormControl;
我是一名优秀的程序员,十分优秀!