繁体   English   中英

如何以Angular 7反应形式设置HTML选择元素的选定值?

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

我在组件中使用Angular 7 reactive forms 我组件的一部分:

@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([])]
    });
  }
}

组件HTML模板相关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>

问题在于,在使用例如admin值更新item之后,它会从服务器的selected属性中获取此值,但在获取数据并显示表格后,它仍以HTML select显示为basic 如何在Angular 7中设置选择? 我知道我可以使用[(ngModel)] = item.selected ,但是当我使用form.controls ,我在控制台中收到警告。

您可以像这样在窗体控件上使用patchValue:

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

}

改进:不要在同一窗体控件中将formControl与formControlName一起使用。 这是更深入的解释的链接

您需要在选项中添加[value]属性

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

沙箱: https//codesandbox.io/s/angular-l0d09

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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