代码之家  ›  专栏  ›  技术社区  ›  AJ-

带FormControl和NgModel问题的角垫表单域

  •  1
  • AJ-  · 技术社区  · 7 年前

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

    我不确定我是否应该使用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 ? 所以我可以用在 下一代模型 直接地 building.radius ?

    抱歉,我对角度很陌生!

    1 回复  |  直到 7 年前
        1
  •  0
  •   AJ-    7 年前

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

    [(ngModel)]="building.radius"
    

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

    推荐文章