简体   繁体   English

如何在Angular Material中不使用ngModel设置双向绑定

[英]How to set two way binding without using ngModel in Angular Material

I am trying to bind a form item to an object without using ngModel. 我试图在不使用ngModel的情况下将表单项绑定到对象。 But it is not working. 但它没有用。

I tried using the [(value)]="" attribute. 我尝试使用[(value)] =“”属性。 However, the initial value of the element changed to "undefined". 但是,元素的初始值更改为“undefined”。

https://material.angular.io/components/input/overview https://material.angular.io/components/input/overview

<mat-form-field class="col-md-4">
    <input matInput placeholder="First name" formControlName="firstCtrl" [(value)]="formData.firstName">
    <mat-error>First name can not be left blank</mat-error>
</mat-form-field>

formData = new RawFormData;

But this one is working correctly: 但是这个工作正常:

<mat-form-field>
    <mat-select placeholder="Title" formControlName="titleCtrl" [(value)]="formData.gender">
          <mat-option *ngFor="let title of personalTitle" [value]="title.value">{{title.viewValue}}</mat-option>
    </mat-select>
</mat-form-field>

value of the input is predefined html attribute and does not emit changes. 输入的value是预定义的html属性,不会发出更改。
In the other hand mat-select is a custom angular component where they declared value as input and output at the same time, something like this: 另一方面, mat-select是一个自定义角度组件,它们同时将value声明为输入和输出,如下所示:

@Input('value') input: any;
@Output('value') output: EventEmitter;

That's why you can bind it in both ways. 这就是为什么你可以用两种方式绑定它。
so in your case either you work with ngModel or do something like this: 所以在你的情况下,你使用ngModel或做这样的事情:

<input (change)="inputValue = $event.target.value" [value]="inputValue"/>

The only way that comes to my mind of doing it without [ngModel] is to use (keyup) . 在没有[ngModel]情况下,我想到的唯一方法就是使用(keyup) I would try to change your input to something like this: 我会尝试将您的输入更改为以下内容:

<mat-form-field class="col-md-4">
          <input matInput placeholder="First name" formControlName="firstCtrl" (keyup)="onKey($event)">
          <mat-error>First name can not be left blank</mat-error>
        </mat-form-field>

and then add a function 然后添加一个函数

onKey(event: any) { // without type info
    formData.gender = event.target.value;
  }

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

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