Reputation: 1313
Here's is my TS code :
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form: FormGroup;
constructor() { }
datas = [{id:1, lib: "London"}, {id:2, lib: "Madrid"}, {id: 3, lib: "Berlin"}]
myCity = "London";
ngOnInit() {
this.form = new FormGroup({
city: new FormControl()
})
}
}
And here is my template :
<form [formGroup]="form" (ngSubmit)="go()">
<select name="" formControlName="city">
<option *ngFor="let data of datas" [value]="data.id" [selected]="myCity == data.lib">{{data.lib}}</option>
</select>
<button type="submit()">click</button>
</form>
I can see my form working properly with my 3 values I can choose. But by default I should see "London" but nothing appear. By default my value is null.
I don't undersand why. My code seems correct
Thank you
Upvotes: 0
Views: 1354
Reputation: 86730
You need to remove formControlName="city"
and your code will work like charm. Reason is you are binding two times one is with formControlName="city"
and another one is with the selected
property.
<form [formGroup]="form" (ngSubmit)="go()">
<select name="">
<option *ngFor="let data of datas" [value]="data.id" [selected]="myCity == data.lib">{{data.lib}}</option>
</select>
<button type="submit()">click</button>
</form>
Upvotes: 1
Reputation: 2416
Remove completely that selected
attribute and modify code where form is created:
city: new FormControl('1') // London has id 1
Upvotes: 1