javascript - Angular 默认下拉值 2 向绑定(bind)

标签 javascript angular typescript angular-reactive-forms

我在 Angular 中有一个下拉列表,它是一个双向绑定(bind)的 FORM 控件。当表单加载时,我想做的就是在绑定(bind)值上设置一个默认值,以便它在下拉列表中显示该值。当我更改下拉列表中的值并打印到控制台时,我看到绑定(bind)是正确的。但是,第一次加载时,默认值不会显示在下拉列表中(未预选)。在此示例中,当表单加载时,“cow”应该是默认选择的项目,但它在页面加载时不起作用。请告知代码中有什么问题。

https://stackblitz.com/edit/angular-error-initial

最佳答案

以编程方式将值分配给您的 FormControl...

   ngAfterViewInit(){
    this.animalControl.setValue(this.animals[2]);
    this.animalControl.markAsTouched();
    console.log('FormControl Value: '+JSON.stringify(this.animalControl.value))
  }

堆栈 Blitz

https://stackblitz.com/edit/angular-error-initial-atr11t?embed=1&file=app/select-hint-error-example.ts


修订

ngModelFormControl 一起使用已被弃用并从 Angular 7 中删除...您应该开始习惯从 FormControl 访问值。

console.log('FormControl Value: '+JSON.stringify(this.animalControl.value))

https://next.angular.io/api/forms/FormControlName#use-with-ngmodel

This has been deprecated for a few reasons. First, developers have found this pattern confusing. It seems like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work, which has understandably caused some confusion.

In addition, this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. Setting the value in the template violates the template-agnostic principles behind reactive forms, whereas adding a FormControl/FormGroup layer in the class removes the convenience of defining forms in the template.

To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

关于javascript - Angular 默认下拉值 2 向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53564034/

相关文章:

angular - Docker/Angular4/Nginx

javascript - 如何从 TypeScript 中的嵌套 JSON 获取数据?

javascript - 通过 props React 将 WS 连接传递给 child

angular - 类型错误 : this. root_ 为空

javascript - 如何获取各种图片 src jQuery

angular - Angular 5 Service Worker可以在后台获取 Assets 吗

angular - 无法弄清楚 TypeScript 错误 TS2304 : Cannot find name

typescript - 并行使用 prisma 和 typescript 模型

javascript - 在 div 中显示绝对定位的图像

javascript - 从以 func 作为参数的 func 获取异常