首页 > 解决方案 > 如何在“输入”之间传递信息

问题描述

我有两个组件“输入”。如何将输入的数据从第一个“输入”(全名)传输到第二个(短名)。

<form [formGroup]="form">
  <div class="row">
   <div class="input-field col s12 m6">
    <input 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">
    <label for="short_name">Short Name</label> 
   </div>
  </div>
</form> 

标签: angular

解决方案


您正在使用 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


推荐阅读