首页 > 解决方案 > 在formGroup中创建新的子formGroup - Angular 6

问题描述

我有一个 Angular 6 应用程序。我有一个像stackblitz下面的表格。

完美的工作样本

但是,我想创建一个共享country-state组件。我想在我需要的时候打电话。所以,我将我的项目转换为下面的 stackblitz。但是,我不想为country-state. 我想从 parent 使用。但是,我无法执行我的第二次 stackblitz。

非工作样本

我怎样才能做到这一点?

标签: angulartypescriptangular6

解决方案


@Input()这是Angular 中装饰器的主要目的:

在您country-state.component.ts 添加Input到您的导入中并使用该装饰器,如下所述:

import { Component, OnInit, Input } from '@angular/core';
...

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

  countries: Country[];
  states: State[];

  @Input() 
  studentForm; // <-- This
...
}

然后在您的 app.component.ts 中将您的子标签更改为:

<app-country-state [studentForm]="studentForm"></app-country-state>

之后,在您的country-state.component.html添加form标签中,如:

<form [formGroup]="studentForm">
    <label>Country:</label> 
    <select formControlName="countryId" (change)="onSelect($event.target.value)">
      <option [value]="0">--Select--</option>
      <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
    </select>
    <br/><br/>

    <label>State:</label>
    <select formControlName="stateId">
      <option [value]="0">--Select--</option>
      <option *ngFor="let state of states " value= {{state.id}}>{{state.name}}</option>
    </select>
 </form>

因此,您不会创建一个新formgroup实例,但您将使用父实例。


推荐阅读