So I've very recently started with Angular development, and there's something that I'm totally missing. I have a basic app set up with app.component.html
as follows:
<h1>{{ routeTitle }}</h1>
<router-outlet></router-outlet>
with app.component.ts
set up as:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
@Input() routeTitle;
}
I then have 2 other basic components set up just to show that my routing works (which they do), but for example on dashboard.component.ts
, I cannot seem to pass routeTitle
from it (being the child component) back up to the Parent (app.component) to display in the H1 tag:
import { Component, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
@Output() routeTitle;
constructor() { }
ngOnInit() {
if (...somelogic...) {
this.routeTitle = 'Dashboard';
}
else {
this.routeTitle = 'Dashboard (Courier)';
}
}
}
Please help, as this is driving me insane as why I can't seem to get my head around something that shouldn't be taking e this long to figure out. Thank you!
The word "child" is used too many places and can be a bit confusing.
This code:
<h1>{{ routeTitle }}</h1>
<router-outlet></router-outlet>
Defines a child route
The input
properties don't work with child routes.
To use the input
property, you need to define the component as a child component ... so something like this:
<h1>{{ routeTitle }}</h1>
<my-child-component [myInputProperty]="myTitle"></my-child-component>
Where the child component is defined as follows:
@Component({
selector: 'my-child-component',
templateUrl: './myChild.component.html'
})
export class MyChildComponent {
@Input() myInputProperty;
// ...
}
I would assume that what you really want to do is pass data between routes? If so, you don't want to use input
/output
properties at all. Rather, you want to use one of the many techniques for passing data between routes.
Plus with Angular v7.2 they just added another technique: https://netbasal.com/set-state-object-when-navigating-in-angular-7-2-b87c5b977bb