I have a JSON data which is being returned when in the Parent component. All you would need to do is type the numbers "12233" or "34567" on the Parent component and you can see on the console the data being printed.
Like in child I want to print the {{firstName}} from using the data from Parent.
Is there a way that data attributes can be passed to the Child component using the routes like in the stackblitz here
Parent: HTML:
<button class="btn-thumbnail">type the secret number to pass</button>
<!-- "number": 12233
or
"number": 34567 -->
TS:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import data from '../data.json';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor(private router: Router) {
document.addEventListener('keypress', this.secretNumber);
}
typed = '';
firstName : any = {};
secretNumber = event => {
this.typed += String.fromCharCode(event.keyCode);
let eraseData = [];
let matchedData = {};
if (this.typed.length == 5) {
Object.keys(data).length > 0 &&
data.items && data.items.userdata.map((item, i) => {
if(item.number == this.typed) {
matchedData = item;
console.log(item);
this.firstName = item.firstName;
console.log(this.firstName);
this.goToChild();
return matchedData;
}
if (item.number != this.typed) {
eraseData.push(item);
}
return eraseData;
});
if (Object.keys(matchedData).length == 0 && eraseData.length > 0 && this.typed.length == 5) {
this.typed = '';
}
}
};
ngOnDestroy() {
document.removeEventListener('keypress', this.secretNumber);
}
ngOnInit() {
}
goToChild() {
this.router.navigate(['/child'], { skipLocationChange: true });
}
}
Data.JSON:
{
"items": {
"userdata": [
{
"firstName": "john",
"lastName": "doe",
"number": 12233
},
{
"firstName": "mary",
"lastName": "jane",
"number": 34567
}
]
}
}
Child: HTML:
<p>
child works! {{firstName}}
</p>