如何在“输入”之间传递信息

时间:2018-11-26 08:41:43

标签: angular

我有两个部分“输入”。如何将输入的数据从第一个“输入”(全名)传输到第二个(简称)。

$(document).ready(function(){
    $("#origin_postal").attr("autocomplete", "disabled");
    });

2 个答案:

答案 0 :(得分:0)

您正在使用ReactiveForm只是订阅full_name控件的事件

import { Component } from '@angular/core';
import {FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form = new FormGroup({
    full_name: new FormControl(),
    short_name: new FormControl()
  })

  constructor() {
    this.form.get('full_name').valueChanges.subscribe(fullName => this.form.get('short_name').setValue(fullName));
  }
}

您可以使用debounceTime等到一定时间后再进行更新

import { Component } from '@angular/core';
import {FormGroup, FormControl } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form = new FormGroup({
    full_name: new FormControl(),
    short_name: new FormControl()
  })

  constructor() {
    this.form.get('full_name').valueChanges.pipe(debounceTime(500)).subscribe(fullName => this.form.get('short_name').setValue(fullName));
  }
}

这是一个有效的示例https://stackblitz.com/edit/angular-ik3pny

答案 1 :(得分:0)

您可以使用模板引用( 选择器)进行此操作,例如:

    <div class="input-field col s12 m6">
    <input #fullNameElement formControlName="full_name" id="full_name" type="text">
    <label for="full_name">Full Name</label> 
   </div>
   <div class="input-field col s12 m6">
    <input formControlName="short_name" id="short_name" type="text" [value]="fullNameElement.value">
    <label for="short_name">Short Name</label> 
   </div>