简体   繁体   中英

How to set selected value of HTML Select Element in Angular 7 reactive forms?

I'm using Angular 7 reactive forms in my component. Part of my component:

@Component({
  selector: 'my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.scss']
})
export class MyFormComponent implements OnInit {
  form: FormGroup;
  loaded: boolean = false;
  item: Item;
  // item gets loaded from the server and looks like this:
  // {
  //   id: 'dksldfkfjdk',
  //   title: 'first',
  //   selected: 'basic'
  // }
  itemsForSelect = ['basic', 'primary', 'admin'];
  isNew: boolean = false;

  constructor(private route: ActivatedRoute,
    private resourceService: ResourceService,
    private fb: FormBuilder,
    private router: Router) {
  }

  ngOnInit() {

    this.resourceService.getItem().subscribe(res => {

      if (res.success) {
        this.item = res.item;
        this.createForm();
        this.loaded = true;
      }
    });
  }

  createForm() {
    this.form = this.fb.group({
      'title': [this.item.title, Validators.compose([])],
      'selected': [this.item.selected, Validators.compose([])]
    });
  }
}

Part of component HTML template related form :

<form [formGroup]="form" (ngSubmit)="isNew ? create() : update()" [class.error]="!form.valid && form.touched">
  <div class="form-group">
    <label for="item"></label>
    <select placeholder="Choose Select" [formControl]="form.controls.selected" class="form-control"
      id="item">
      <option *ngFor="let itemForSelect of itemsForSelect">{{ itemForSelect }}</option>
    </select>
  </div>
  <button class="btn btn-primary udpate pointer" [disabled]="!form.valid" type="submit">
    {{ isNew ? 'Create' : 'Update' }}
  </button>
</form>

The problem is that after updating item with, for example admin value, it has this value from server in property selected , but it still shows basic in HTML select as selected, after fetching data and showing form. How to set selected in Angular 7? I know I can use [(ngModel)] = item.selected , but as I'm using form.controls , I'm getting warning in console.

You can use patchValue on your form control like that:

public updateValue() {
this.form.get('selected').patchValue('basic');

}

Improvement: Dont use formControl with formControlName in same form control. Here is link to deeper explanation

You need to add [value] property to options

 <option
        [value]="itemForSelect"
        *ngFor="let itemForSelect of itemsForSelect"
  >{{ itemForSelect }}</option>

Sandbox: https://codesandbox.io/s/angular-l0d09

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM