I've created a private npm package which I can run in my other apps using this code in the html:
<app-header-name></app-header-name>
This is the code in the npm package it runs:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header-name',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
public blob: any;
constructor() {}
ngOnInit(): void {
console.log(this.blob);
}
}
And this is the html code in the npm package:
<div class="row">
<div class="col d-flex justify-content-center">
Click the button to download the template
</div>
</div>
My question is, how do I pass over a variable from my app to go into the variable blob in the npm package? I have tried the following, which just console logged 'undefined':
<app-header-name blob="bazinga"></app-header-name>
Also, is there a way to pass data back from the npm package? For example, it will take in the string blob variable, then add another word to it and pass it back to the main app?
CodePudding user response:
you need to add a input in your component.
import { Component, EventEmitter, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-header-name',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
@Input() blob: any;
@Output() somethingOut = new EventEmitter();
ngOnInit(): void {
console.log(this.blob);
}
sendToParent() {
this.somethingOut.emit({ data: 'Hello from child component '});
}
}
passing in a string
<app-header-name blob="bazinga"></app-header-name>
passing in a variable from the parent
<app-header-name [blob]="someVarOnTheParent"></app-header-name>
passing in and out a variables
the parent component will need a function to receive the data.
Notice the $event
is needed since the child is passing data
<app-header-name [blob]="someVarOnTheParent" (somethingOut)="parentFunc($event)"></app-header-name>