将反应形式值发送到另一个组件

时间:2018-03-11 13:11:46

标签: angular typescript rxjs

我有abc.component.html,其中包含反应式表单组件。

<form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)">
  <div>
    <div style="padding-bottom: 5px;">
      <label for="name">Username : </label>
      <input type="text" name="username" id="username" formControlName="username">
    </div>
    <div *ngIf="!rForm.controls['username'].valid && rForm.controls['username'].touched">This is required</div>
    <div style="padding-left:11px">
      <label for="name">Address : </label>
      <input type="text" name="address" id="address" formControlName="address">
    </div>
    <div>
      <input type="submit" value="Submit Form" [disabled]="!rForm.valid">
    </div>
  </div>
</form>
<div>
<h2>{{username}}</h2>
<h1>{{address}}</h1>
<h1>{{rForm.value | json}}</h1>
<h1>{{rForm.value.username}}</h1>
</div>

下面给出了相应的ts文件 -

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  rForm: FormGroup;
  post: any;
  address: string = '';
  username: string = '';

  constructor(private fb: FormBuilder) {
    this.rForm = fb.group( {
      'username' : [null, Validators.required],
      'address' : [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])],
    }
    );

  }
  addPost(post) {
      this.address = post.address;
      this.username = post.username;
  }
}

在另一个组件上(没有父子关系)我试图发送整个表单值。

有没有办法将此表单值发送到另一个组件,以便我可以根据需要使用每个元素值。

0 个答案:

没有答案