There are many ways. This example uses distribution between parent and child elements. It is very effective.
I presented an example that allows you to view the use of two methods of data binding in two forms. If someone can provide a plunkr sample, that would be very good ;-)
You can search for another way using your service provider. You can watch this video for reference too: ( Exchange of data between components in Angular )
mymodel.ts (data for exchange)
// Some data we want to share against multiple components ... export class mymodel { public data1: number; public data2: number; constructor( ) { this.data1 = 8; this.data2 = 45; } }
Remember: there must be a parent who shares "mymodel" with the child components.
Parent component
import { Component, OnInit } from '@angular/core'; import { mymodel } from './mymodel'; @Component({ selector: 'app-view', template: ' <app-mychild [model]="model" > </app-mychild>' <app-mychild [model]="model" > </app-mychild>', }) export class MainComponent implements OnInit { public model: mymodel; constructor() { this.model = new mymodel(); } ngOnInit() { } }
Child component, mychild.component.ts
import { Component, OnInit,Input } from '@angular/core'; import { FormsModule } from '@angular/forms'; // <-- NgModel lives here 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 ; // Here keywork @Input() is very important it indicates that model is an input for child component constructor() { } ngOnInit() { } }
Note. In some rare cases, an error may occur while parsing the HTML code, because the model is not "ready" for use in page initialization. In this case, add the ngIf condition to the HTML code:
<div *ngIf="model"> {{model.data1}} </div>
sancelot Jul 24 '17 at 7:26 2017-07-24 07:26
source share