私は最初のアングル2アプリケーションを作成しようとしています。そしていつものように、私は即座に私が作りたいモデルに悩まされています。私は、芸術家の間に親子関係を作るためのモデルを持っています。 例えば:私は次のようにいくつかの子オブジェクトで私のバスケットに記事を追加したい:アングル2/4アライメント付き反応形式
typescriptですでIArticle[] = [
{
id: 1,
parentArticle: 1234596,
description: 'some description for parent'
children: [
{
id: 1,
childArticle: 123457,
childDescription: 'some description for first child'
},
{
id: 2,
childArticle: 123467,
childDescription: 'some description for second child'
},
.....
]
私は私の記事のためのインタフェースを定義しました。子オブジェクトは、わずかに異なる独自のインターフェースを持っています。
これらの子オブジェクトは小さな固定セットなので、これらの子をドロップダウンリストを使用して追加したいと考えています。私は、これらのオブジェクトをクリックして削除するボタンとして表示するようにします(オプションのモーダルポップアップでオプションです)。だから私はドロップダウンリストの横にあるボタンは、ドロップダウンリストの値を配列に追加するべきだと思った。これは正常な型付き配列に値を追加したときにうまく動作します。しかし今、私はこの配列を「反応型」にまとめたいと思います。
これらのリアクティブフォームで配列を操作する方法と、フォームコントロールオブジェクトにそれらをラップする方法を教えてもらえますか?私はFormArray "control"を見ましたが、これが私が探しているものであるかはわかりません。これは一連のFormControlsを継ぎ合わせています。データの配列ではありません。おそらく反応型は正しい決定ではないでしょうか?うまくいけば誰かが私を正しい軌道に乗せることができます。
マイHTMLテンプレートは、(コードから剥離ブートストラップコード)
<form autocomplete="off">
<input type="text" Placeholder="Article Number" />
<div >
<button *ngFor="let child of children">
<span class="glyphicon glyphicon-remove-circle text-danger"></span>
{{ child.childArticle }}
</button>
</div>
<div >
<select class="form-control inline">
<option value="">Select Service..</option>
<option *ngFor="let serviceOption of serviceOptions" [ngValue]="serviceOption.serviceNumber">
{{serviceOption.serviceDescription}}
</option>
</select>
<button (click)="onAddService()">
Add
</button>
</div>
<div>
<button type="submit">
Save
</button>
</div>
</form>
種類よろしくを、以下の通りです。
------ typescriptですコード:
export class NewServiceComponent implements OnInit {
newServiceForm: FormGroup;
serviceOptions: IServiceArticle[] = [
{ 'id': 1, 'serviceNumber': 123456, serviceDescription: 'description 1' },
{ 'id': 2, 'serviceNumber': 456789, serviceDescription: 'description 2' },
{ 'id': 3, 'serviceNumber': 123456, serviceDescription: 'description 3' },
];
selectedServiceOption: IServiceArticle;
newArticle: IService;
constructor(private _fb: FormBuilder) {
}
createForm() {
this.newServiceForm = this._fb.group({
services: this._fb.array([]),
articleNumber: this._fb.control(null, Validators.required),
})
}
ngOnInit() {
this.createForm();
}
onAddService() {
const arrayControl = <FormArray>this.newServiceForm.controls['services'];
let newgroup = this._fb.group({
serviceNumber: this.selectedServiceOption.serviceNumber,
serviceDescription: this.selectedServiceOption.serviceDescription,
})
arrayControl.push(newgroup);
}
}
「選択」について不思議に思うのは、ユーザーが同じ値を何度も繰り返し選択できるということですか?この時点で – Alex
できました。それを避けるために、検証ロジックを更新する必要があります。角を理解するために、これは現時点で問題ではありません。 –
ねえ、答えはどうやっていったの?助けが必要なの? :) – Alex