angular - 在formGroup中创建新的子formGroup - Angular 6
问题描述
我有一个 Angular 6 应用程序。我有一个像stackblitz下面的表格。
但是,我想创建一个共享country-state
组件。我想在我需要的时候打电话。所以,我将我的项目转换为下面的 stackblitz。但是,我不想为country-state
. 我想从 parent 使用。但是,我无法执行我的第二次 stackblitz。
我怎样才能做到这一点?
解决方案
@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
实例,但您将使用父实例。
推荐阅读
- sed - 如何让 sed 自动运行(长)同义词表?
- angular - 防止 Angular7 项目在控制台中发送垃圾邮件/泛滥错误
- angular - 访问spec.ts,Angular6中的私有变量
- scala - Scala for-comprehension with Option and Some,由 ReaderT 包装
- caddy - Caddy URL 从 blog.mysite.com 重写为 mysite.com/blog
- node.js - 如何在 Node.js 中实现 Kerberos?
- node.js - 如何使用 Nodejs 在 RabbitMQ 中实现远程过程调用(RPC)
- django - 带有redis的django频道:在建立websocket连接之前创建的消息丢失
- aimms - 如何为 AIMMS 约束设置索引域
- node.js - 为一组串行命令解析具有不同 ByteLength 的数据