I need to get the selected value of the dropdown and upload file details on submit button click in a angular application.
HTML:
<div>
<div *ngFor="let item of controls; let pointIndex=index" [formGroupName]="pointIndex">
<label>
Selling Point: <select>
<option *ngFor="res of objArrValues" [value]="res.value">{{res.name}}</option>
</select>
</label>
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files, pointIndex)">
<button type="button" (click)="deleteSellingPoint(pointIndex)">Delete</button>
</div>
<button type="button" (click)="getDetails()">Add</button>
</div>
Typescript (Something like this):
getDetails()
{
//something like a array of controls to iterate and get the values
for(let i=0; i< controls.length; i++)
{
obj.id = arr[i].dropdownValue;
obj.file = arr[i].selectedFile;
}
}
i tried to do it in the change event of both the controls which didn't work. Is there anyway to iterate over the controls on submit and get the values?
答案 0 :(得分:1)
you dont need to do that to get the select value just use ngModel:
<select [(ngModel)]="selectValue">
<option *ngFor="res of objArrValues" [value]="res.value">{{res.name}}</option>
</select>
and declare a variable in you're ts file named selectValue,You can do this also for your input.
答案 1 :(得分:0)
您还可以在如下所示的select语句中使用(更改)事件,
<select (change)="onChange($event.target.value)">
<option *ngFor="let res of objArrValues" [value]="res.value">
{{res.name}}
</option>
</select>
在您的.ts文件中,您可以使用类似onChange函数的选定值,
onChange(selectedValue)
{
//you will get the selected value here
}
答案 2 :(得分:0)
我认为您想要的是formArray的用法。在这里查看如何使用该https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/
在您的情况下,其外观大致如下:
TS:
@Component(...)
class MyComp {
public form:FormGroup = this.fb.group({
someKey: this.fb.array([ // This is the array of controls we iterate over
this.fb.group({/*...*/}), // Each entry in your array
this.fb.group({/*...*/}) // And another entry in your array
])
});
constructor(private fb:FormBuilder) {}
public getDetails() {
const formValueAsArray = this.form.get('someKey').value; // Just get the value as a normal array
// now do what you want with the array
}
}
模板:
<div>
<!-- Only changed the following line -->
<div *ngFor="let item of form.get('someKey').controls; let pointIndex=index" formArrayName="someKey">
<label>
Selling Point: <select>
<option *ngFor="res of objArrValues" [value]="res.value">{{res.name}}</option>
</select>
</label>
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files, pointIndex)">
<button type="button" (click)="deleteSellingPoint(pointIndex)">Delete</button>
</div>
<button type="button" (click)="getDetails()">Add</button>