【问题标题】:Angular Reactive Forms binding two field in seperate FormsAngular Reactive Forms 在单独的表单中绑定两个字段
【发布时间】:2018-11-11 08:22:37
【问题描述】:

我想要两个以两种不同的反应形式绑定到值。 所以我有一个组件作为主要女巫,包括两个单独的组件,例如组件一和组件二。他们每个人都有一个表格。 因此,在组件一中,字段名称 - 也在组件二中。 当我从一个字段更改值时,它必须绑定到另一个字段。 也许这里有人可以给我一个小提示如何做到这一点。

【问题讨论】:

  • 到目前为止你试过什么代码在哪里?
  • 基本组件交互在angular.io/guide/component-interaction有详细解释。我建议先阅读文档,然后自己尝试,然后询问其他人。

标签: angular forms binding reactive


【解决方案1】:

根据您的问题,您的 html 页面上似乎有两个单独的组件,并且希望在它们之间提供交互。

要实现这一点,您应该在组件之间使用共享服务,它允许交互。

你应该关注这个:Communicate between component via a service,文章还列出了其他的交流方式,看看。

【讨论】:

  • 是的,这正是我想做的。谢谢你的提示。我会弄清楚的。
【解决方案2】:

我的解决方案:

创建服务

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class ComponentInteractionService {
  public name = new Subject<string>();
}

组件 A:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ComponentInteractionService } from '../../services/component-interaction.service';

@Component({
  selector: 'app-form-eins',
  templateUrl: './form-eins.component.html',
  styleUrls: ['./form-eins.component.css']
})
export class FormEinsComponent implements OnInit {

  formEins: FormGroup;

  constructor(private fb: FormBuilder,
    private ci: ComponentInteractionService) { }

  submit() {
    this.ci.name.next(this.formEins.get("nameEins").value);
  }

  ngOnInit() {

    this.formEins = this.fb.group({
      nameEins: ''
    });

    this.ci.name.subscribe( 
      data => { this.formEins.get("nameEins").setValue(data); }
    );   

  }

}

组件 B:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ComponentInteractionService } from '../../services/component-interaction.service';

@Component({
  selector: 'app-form-zwei',
  templateUrl: './form-zwei.component.html',
  styleUrls: ['./form-zwei.component.css']
})
export class FormZweiComponent implements OnInit {

  formZwei: FormGroup;

  constructor(private fb: FormBuilder,
    private ci: ComponentInteractionService) { }

  submit() {
    this.ci.name.next(this.formZwei.get("nameEins").value);
  }

  ngOnInit() {

    this.formZwei = this.fb.group({
      nameEins: ''
    });

    this.ci.name.subscribe( 
      data => { this.formZwei.get("nameEins").setValue(data); }
    ); 

  }

}

【讨论】:

    猜你喜欢
    • 2019-04-10
    • 2017-09-02
    • 2022-08-14
    • 2020-04-07
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多