繁体   English   中英

Angular 中此代码中 ngModel 的替代品是什么,因为我收到有关同时使用表单控件名称和 ngModel 的警告

[英]What is the replacement for ngModel in this code in Angular as I am getting warning for using form control name and ngModel together

我一起使用ngModelformControlName ,所以我在控制台中收到警告。 我想删除该警告,但我无法弄清楚我是否正在删除其中的ngModel ,而不是我应该用什么替换它。 我尝试了几个代码,但没有用。

这是我的 component.html 文件:

<mat-select
    formControlName="store"
    [(ngModel)]="this.form.value['store']"
    (selectionChange)="changestore()"
    multiple>
</mat-select>

这是我的 component.ts

changestore(){
 this.storeTechData.forEach((element:any)=> {
  if(this.form.value['store'].includes(element['store_id'])){
     element['active'] = true;
     }else{
      element['active'] = false;
     }
   });
 }

我尝试了反应形式和东西,但我没有得到要求的 output。有人请用反应形式或任何其他东西替换ngModel ,这样我将得到所需的 output,并且控制台中也不会出现警告

关于Angular中的forms:

在您的应用程序中构建 forms 时,您将希望坚持一种范例。 换句话说,您将想要使用ngModelformControlName但不能同时使用两者(这就是为什么 Angular 会警告您如果两者都包含在表单元素中)

反应性

component.html

<form [formGroup]="form">
  <mat-select
    formControlName="store"
    (selectionChange)="changestore()"
    multiple>
  </mat-select>
</form>

component.ts

form = new FormGroup({
  store: new FormControl('')
})

模板驱动component.html

<form>
  <mat-select
    [(ngModel)]="store"
    (selectionChange)="changestore()"
    multiple>
  </mat-select>
</form>

component.ts

store: string = ''

一般来说,反应式 forms 是一种更强大的整体学习范例,因此我建议您熟悉这种方法( 两者各有利弊)。 但是对于这个简单的用例,任何一种方法都可以,并且取决于个人喜好

注意:我没有尝试解决与changestore function 相关的任何问题,因为我不太确定它试图实现什么并且缺少一些实现细节。 但希望这足以让你弄清楚自己需要做什么

暂无
暂无

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

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