我有一系列表格(每个表格由1个组件管理)。
这些表单中有一种输入模式(例如,其中许多需要允许输入地址)我必须重构为可重用的组件,因为它们以多种形式使用,我不想复制既不是他们的逻辑也不是他们的模板。
每个可重复使用的组件都必须
<form>
标记address: {street: "...", "city": "...", ...}
)从Angular2的this tutorial开始,我了解如何实现目标 1 , 2 和 4 。
本教程中的解决方案还允许实现其他目标,但它通过从父执行所有操作来实现(参见app.component.ts#initAddress
)。
如何在声明控件时实现 3 , 5 , 6 和 7 他们在孩子中的限制?
答案 0 :(得分:13)
如果你想提供子组件中的所有内容,你可以尝试这样的事情。
import { Component, Input } from '@angular/core';
import { FormGroupDirective, ControlContainer, Validators, FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'address',
template: `
<div formGroupName="address">
<input formControlName="city" placeholder="city" (blur)="onTouched" />
<input formControlName="country" placeholder="country" (blur)="onTouched" />
<input formControlName="zipCode" placeholder="zipCode" (blur)="onTouched" />
</div>
`,
styles: [`h1 { font-family: Lato; }`],
viewProviders: [
{ provide: ControlContainer, useExisting: FormGroupDirective }
]
})
export class AddressComponent {
private form: FormGroup;
constructor(private parent: FormGroupDirective) { }
ngOnInit() {
this.form = this.parent.form;
const city = new FormControl('', Validators.required);
const country = new FormControl('', Validators.required);
const zipCode = new FormControl('', Validators.required);
const address = new FormGroup({ city, country, zipCode });
this.form.addControl('address', address);
}
}
用法:
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
<address></address>
</form>
{{ form.value | json }}
`,
styleUrls: ['./app.component.css'],
})
export class AppComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({});
}
}
请注意我正在使用ReactiveFormsModule
。
另请务必查看Angular Forms - Kara Erickson。该演示文稿向您展示了如何使用模板驱动和反应形式的实现来创建可重用的地址组件。
答案 1 :(得分:0)
您不应该使用此类实施。使用ControlValueAccessor更加干净。
ControlValueAccessor是一个接口,允许角形式模块(经典或反应)写入值或状态,并注册回调以检索更改和事件。
writeValue(value: Address): void { } // Allows angular to set a default value to the component (used by FormControl or ngModel)
registerOnChange(fn: (_: any) => void): void {} // Callback to be called when the component value change.
registerOnTouched(fn: (_: any) => void): void { } // Callback to be called when a "touch" event occurs on the component
setDisabledState(isDisabled: boolean): void { } // Allows angular to update the component disable state.
但您还需要提供NG_VALUE_ACCESSOR
我为地址组件写了这个快速而又脏的例子:
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Address } from './address';
@Component({
selector: 'app-address-input',
template: `
<label for="number">Num: </label>
<input type="number" [disabled]="disabled" name="number" id="number" (change)="numberUpdate($event)" value="{{value.num}}"/><br />
<label for="street">Street: </label>
<input type="text" [disabled]="disabled" (change)="streetUpdate($event)"name="street" id="street" value="{{value.street}}" /><br />
<label for="city">City: </label>
<input type="text" [disabled]="disabled" name="city" id="city" value="{{value.city}}" (change)="cityUpdate($event)" /><br />
<label for="zipCode">Zip Code: </label>
<input type="text" [disabled]="disabled" name="zipCode" id="zipCode" value="{{value.zipCode}}" (change)="zipCodeUpdate($event)" /><br />
<label for="state">State: </label>
<input type="text" [disabled]="disabled" name="state" id="state" value="{{value.state}}" (change)="stateUpdate($event)" /><br />
<label for="country">Country: </label>
<input type="text" [disabled]="disabled" name="country" id="country" value="{{value.country}}" (change)="countryUpdate($event)" />`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AddressInputComponent) // forward the reference,
multi: true // allow multiple component in the same form
}]
})
export class AddressInputComponent implements ControlValueAccessor {
private _onChange = (_: any) => {};
private _onTouched = (_: any) => {};
disabled = false;
private _value: Address = {num: undefined, street: undefined, city: undefined, state: undefined, zipCode: undefined, country: undefined}; // current value (Address is just an interface)
set value(value: Address) { // interceptor for updating current value
this._value = value;
this._onChange(this._value);
}
get value() {
return this._value;
}
writeValue(value: Address): void {
if (value && value !== null) {
this._value = value;
}
}
registerOnChange(fn: (_: any) => void): void {
this._onChange = fn;
}
registerOnTouched(fn: (_: any) => void): void {
this._onTouched = fn; // didn't used it but you should for touch screen enabled devices.
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
numberUpdate(event: any) {
// additional check or process
this._updateValue(event.target.value, 'num')
}
streetUpdate(event: any) {
// additional check or process
this._updateValue(event.target.value, 'street')
}
cityUpdate(event: any) {
// additional check or process
this._updateValue(event.target.value, 'city')
}
zipCodeUpdate(event: any) {
// additional check or process
this._updateValue(event.target.value, 'zipCode')
}
stateUpdate(event: any) {
// additional check or process
this._updateValue(event.target.value, 'state')
}
countryUpdate(event: any) {
// additional check or process
this._updateValue(event.target.value, 'country');
}
private _updateValue(value: any, field: string) {
const newValue = this._value;
newValue[field] = value;
this.value = newValue;
}
}
然后在表单中使用它像任何其他表单元素:
<form [formGroup]="registerForm">
<app-address-input formControlName="address"></app-address-input>
</form>
您可以在组件中添加更多逻辑。这是一个有效的例子。请记住它是一个简单的例子,应该重新编写清洁代码。