My goal is to construct a parent component called Action
, which includes two child components named Infos
and Localisation
. I want to connect the inputs of the children with the parent model.
This is the model:
export class Action{
title: string;
location = new Location();
}
export class Location{
region: string;
department: string;
}
The parent Component:
import { Component, OnInit } from '@angular/core';
import {InfosComponent} from './infos.component';
import {LocationComponent} from './location.component';
import {Action} from './action';
import { ActionService } from './action.service';
@Component({
selector: 'form-action',
template: `
<h1>Action Form {{currentAction.title}}</h1>
<infos [title]="currentAction.title"></infos>
<location [location]="currentAction.location"></location>
<button (click)="addAction(currentAction)">Add</button>
<h2>My actions</h2>
<ul>
<li *ngFor="let act of actions">
{{act.title}} ({{act.location.region}}-{{act.location.department}})
</li>
</ul>
`,
directives: [InfosComponent,LocationComponent],
providers : [ActionService]
})
export class ActionComponent implements OnInit{
currentAction : Action;
actions : Action[];
constructor(private actionService: ActionService) {
this.currentAction =new Action();
console.log(this.currentAction);
}
addAction(action){
console.log (action);
this.actionService.saveAction(action);
}
getActions(){
this.actionService.getActions().then(actions => this.actions = actions);
}
ngOnInit() {
this.getActions();
}
}
The location component:
import { Component, Input } from '@angular/core';
import {Location} from './action';
@Component({
selector: 'location',
template: `
<h2>Location</h2>
<p>
<label for="region">Region: </label>
<input id="region" [(ngModel)]="location.region" placeholder="Region"/>
</p>
<p>
<label for="department">Department: </label>
<input id="department" type="text" [(ngModel)]="location.department" placeholder="Department"/>
</p>
`
})
export class LocationComponent {
@Input("location") location: Location;
}
The infos component:
import { Component, Input } from '@angular/core';
@Component({
selector: 'infos',
template: `
<h2>Information</h2>
<p>
<label for="title">Title: </label>
<input id="title" [(ngModel)]="title" placeholder="Title"/>
</p>
`
})
export class InfosComponent {
@Input() title: string;
}
When creating a new action, the location is saved but the title is not included in the new action. It works when passing the entire action to the Infos
component (not just the title). However, it does not work with a string type.