【问题标题】:Angular mat-form-field with FormControl and NgModel issue带有 FormControl 和 NgModel 问题的 Angular mat-form-field
【发布时间】:2019-02-05 10:18:18
【问题描述】:

我有一个带有type="number" 输入框的mat-form-field

我不确定我是否应该使用 FormControl 或 NgModel。

我有一个recieves 输入对象的子组件,我应该将输入字段中写入的内容保存到该对象的属性中。

这是我的子控制器:

@Input()
  building: Building;  

@ViewChild("numberMatInput", {read: MatInput})
  numberMatInput: MatInput;
  numberInput: FormControl = new FormControl();

ngOnInit() {
    this.numberInput.valueChanges
    .subscribe(s => {
      this.building.radius = s;
    });
}

我的观点是:

<mat-form-field appearance="outline">
     <mat-label>KM</mat-label>
     <input type="number" matInput #numberMatInput [formControl]="numberInput">
</mat-form-field>
<mat-icon matListIcon (click)="numberInput.setValue('')">close</mat-icon>

所以它可以工作,输入值被保存到对象属性 -> this.building.radius 但什么不起作用,这是一个可以在选择建筑物时打开的面板,如果我关闭面板并打开它同样,输入字段为空,而不是在关闭面板之前显示最新值。

我应该使用NgModel吗?所以我可以直接在NgModel 上使用building.radius 吗?

抱歉,我对 Angular 还很陌生!

【问题讨论】:

  • 如果您正在使用Template driven forms,则使用ngModel,或者使用Reactive forms,然后使用FormControl
  • 你的角度版本是什么?
  • 我正在使用 Angular 6.1.1

标签: angular angular-ngmodel form-control


【解决方案1】:

现在我这样解决了,从 FormControl 更改为:

[(ngModel)]="building.radius"

就是这样,所以它直接写在对象的属性上,不确定是否是最好的方法,但它可以工作

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2021-04-09
    • 2020-04-30
    • 2020-05-03
    相关资源
    最近更新 更多