Reputation: 1606
My html looks like below
<div>My app
<form [formGroup]="selectForm">
<select [formControl]="selectForm.controls['filename']">
<option *ngFor="let item of files; let i = index;" [value]="item" [selected]="i==0">{{item}}</option>
</select>
<button type="submit" [disabled]="!selectForm.valid">Submit</button>
</form>
</div>
My component is as below
export class App {
files: Array<any>=[];
selectForm: FormGroup;
name:string;
constructor(private _formbulider: FormBuilder) {
this.selectForm = this._formbulider.group({
'filename': ['', Validators.required]
});
this.files = [1];
}
}
But my problem is submit is disabled since form is invalid. I expect form to be valid. Plunkr link is here
Upvotes: 2
Views: 958
Reputation: 1499
You can initialize field with value, like this:
'filename': [this.files[0], Validators.required]
Then you can remove [selected]
tag from HTML code.
* Edit
Another option is to use ngModel directive and that's the way I prefer the most.
Check the plnkr with updated code.
Upvotes: 3
Reputation: 13558
Change your component as below :
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<div>My app
<form [formGroup]="selectForm">
<select formControlName="filename">
<option *ngFor="let item of files; let i = index;" [value]="item" [selected]="i==0">{{item}}</option>
</select>
</form>
<button type="submit" [disabled]="!selectForm.valid"> Submit </button>
</div>
`,
})
export class App {
files: Array<any>=[];
selectForm: FormGroup;
name:string;
constructor(private _formbulider: FormBuilder) {
this.files = [1,2,4,5,6];
this.selectForm = _formbulider.group({
filename: [this.files[0], Validators.required]
});
}
}
Upvotes: 0