多くの方法があります。これは、親要素と子要素の間の伝播を使用した例です。これは非常に効率的です。
2つのフォーム内で2つの方法のデータバインディングの使用法を表示できる例を提出しました。誰かがplunkrサンプルを提供できるなら、これはとてもいいでしょう;-)
サービスプロバイダーを使用して別の方法を探すことができます。参考までにこのビデオもご覧ください:(Angularのコンポーネント間でデータを共有する)
mymodel.ts(共有するデータ)
export class mymodel {
public data1: number;
public data2: number;
constructor(
) {
this.data1 = 8;
this.data2 = 45;
}
}
注意:子コンポーネントと「mymodel」を共有する親が必要です。
親コンポーネント
import { Component, OnInit } from '@angular/core';
import { mymodel } from './mymodel';
@Component({
selector: 'app-view',
template: '<!-- [model]="model" indicates you share model to the child component -->
<app-mychild [model]="model" >
</app-mychild>'
<!-- I add another form component in my view,
you will see two ways databinding is working :-) -->
<app-mychild [model]="model" >
</app-mychild>',
})
export class MainComponent implements OnInit {
public model: mymodel;
constructor() {
this.model = new mymodel();
}
ngOnInit() {
}
}
子コンポーネント、mychild.component.ts
import { Component, OnInit,Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { mymodel } from './mymodel';
@Component({
selector: 'app-mychild',
template: '
<form #myForm="ngForm">
<label>data1</label>
<input type="number" class="form-control" required id="data1 [(ngModel)]="model.data1" name="data1">
<label>val {{model.data1}}</label>
label>data2</label>
<input id="data2" class="form-control" required [(ngModel)]="model.data2" name="data2" #data2="ngModel">
<div [hidden]="data2.valid || data2.pristine"
class="alert alert-danger">
data2 is required
</div>
<label>val2 {{model.data2}}</label>
</form>
',
})
export class MychildComponent implements OnInit {
@Input() model: mymodel ;
constructor() {
}
ngOnInit() {
}
}
注:まれに、ページの初期化時にモデルを使用する準備ができていないため、HTMLコードの解析時にエラーが発生する場合があります。この場合、HTMLコードの前にngIf条件を付けます。
<div *ngIf="model"> {{model.data1}} </div>