【问题标题】:Angular 5 ngModel setting default value based on form inputAngular 5 ngModel 根据表单输入设置默认值
【发布时间】:2018-04-28 21:33:14
【问题描述】:

我有一个使用 Firebase 的实时数据库在 Angular 5 中构建的应用程序。我的表单使用的是 ngModel,并且有一个用户 ID 字段和一个自定义用户名字段。我需要用户名具有用户 ID 的默认值,除非用户选择更改它。

<label class="label-control" for="idInput">User Name</label>
<input id="userId" type="text" for="idInput" class="form-control"
       required minlength="1" name="userId"
       [(ngModel)]="userData.userId"
       #userId="ngModel"
       placeholder="e.g. johnhancock1776"
       />

<label class="label-control" for="vanityInput">Your Custom URL</label>
<input id="vanityId" type="text"
       for="vanityInput" 
       class="form-control"
       name="vanityId"
       [(ngModel)]="userData.vanityId"
       value="{{userData.userId}}"
       #vanityId="ngModel"
       placeholder="custom url" />

当用户输入他们的用户 ID 时,虚 id 字段会填充,但不会将数据发送到数据库,除非他们在虚字段中添加或删除某些内容。

我尝试添加:

       [ngModelOptions]="{updateOn: 'submit'}"

如果两个字段都没有被触及,女巫让它发送一个空字符串,但当只更改用户 ID 时不会发送任何内容。

【问题讨论】:

    标签: angular forms firebase-realtime-database form-control ngmodel


    【解决方案1】:

    您可以使用(ngModelChange) 事件来更改userData.vanityId 的值而不是value="{{userData.userId}}",因为您只更改视图而不是userData.vanityId 值。

    component.html

    <label class="label-control" for="idInput">User Name</label>
    <input id="userId" type="text" for="idInput" class="form-control"
           required minlength="1" name="userId"
           [(ngModel)]="userData.userId"
           #userId="ngModel"
           placeholder="e.g. johnhancock1776"
           (ngModelChange)="changeVanityId($event)"
           />
    <br>
    <label class="label-control" for="vanityInput">Your Custom URL</label>
    <input id="vanityId" type="text"
           for="vanityInput" 
           class="form-control"
           name="vanityId"
           [(ngModel)]="userData.vanityId"
           #vanityId="ngModel"
           placeholder="custom url" />
    
    <button (click)="sendBackend()">Send</button>
    

    我添加了一个按钮来打印 userData 值以验证打印的值是否正确。

    组件.ts

      /**
       * Print in console
       */
      sendBackend() {
        console.log(this.userData);
      } 
    
      /**
       * Change value of vanityId
       */
      changeVanityId(event) {
        this.userData.vanityId = event
      }
    

    我在这里实现这个:https://stackblitz.com/edit/angular-sadk7e

    【讨论】:

      猜你喜欢
      • 2017-06-11
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      相关资源
      最近更新 更多