How to load dynamic components based on a property from object? - javascript

I'm trying to build a list of cards which may contain different components; So for example I have the following array of objects:
{
title: 'Title',
descrption: 'Description',
template: 'table',
},
{
title: 'Title',
descrption: 'Description',
template: 'chart',
}
I get this array as a response from a service, then I need to match each of thos objects to a component based on the template property, so for example, the first item should match to the TableComponent and the second one to the ChartComponent;
I'm trying to follow the Angular Docs regarding Dynamic Component Loading, but I'm not sure how tell the method how to match each object in the array to a specific component.
In my parent component I have made an anchor point where the components should load with a directive:
<ng-template appCheckpointHost></ng-template>
And I'm trying to use the ComponentFactoryResolver as it shows in the example.
loadComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChartCheckpointComponent);
const viewContainerRef = this.checkHost.viewContainerRef;
}
The example shows a scenario in which the "service" runs every three seconds, gets a random item, and shows it; but what I'm trying to do instead is to fetch all the items when the parent component loads, and render each item with its respective component.
Any ideas to get this to work?

You can create a dictionary like:
const nameToComponentMap = {
table: TableComponent,
chart: ChartComponent
};
And then just use this dictionary to determine which component should be rendered depending on the template property of particular item in your items array:
const componentTypeToRender = nameToComponentMap[item.template];
this.componentFactoryResolver.resolveComponentFactory(componentTypeToRender);

You can view my blog here
First I will need to create a directive to reference to our template instance in view
import { Directive, ViewContainerRef } from "#angular/core";
#Directive({
selector: "[dynamic-ref]"
})
export class DynamicDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
Then we simply put the directive inside the view like this
<ng-template dynamic-ref></ng-template>
We put the directive dynamic-ref to ng-content so that we can let Angular know where the component will be render
Next I will create a service to generate the component and destroy it
import {
ComponentFactoryResolver,
Injectable,
ComponentRef
} from "#angular/core";
#Injectable()
export class ComponentFactoryService {
private componentRef: ComponentRef<any>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
createComponent(
componentInstance: any,
viewContainer: any
): ComponentRef<any> {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
componentInstance
);
const viewContainerRef = viewContainer.viewContainerRef;
viewContainerRef.clear();
this.componentRef = viewContainerRef.createComponent(componentFactory);
return this.componentRef;
}
destroyComponent() {
if (this.componentRef) {
this.componentRef.destroy();
}
}
}
Finally in our component we can call the service like this
#ViewChild(DynamicDirective) dynamic: DynamicDirective;
constructor(
private componentFactoryService: ComponentFactoryService
) {
}
ngOnInit(){
const dynamiCreateComponent = this.componentFactoryService.createComponent(TestComponent, this.dynamic);
(<TestComponent>dynamiCreateComponent.instance).data = 1;
(<TestComponent>dynamiCreateComponent.instance).eventOutput.subscribe(x => console.log(x));
}
ngOnDestroy(){
this.componentFactoryService.destroyComponent();
}
/////////////////////////////////
export class TestComponent {
#Input() data;
#Output() eventOutput: EventEmitter<any> = new EventEmitter<any>();
onBtnClick() {
this.eventOutput.emit("Button is click");
}
}

Related

Angular Material Data Table That Hits API endpoint

I'm trying to create a Angular Material Table that displays dynamic data coming from an API endpoint but only the Table Header populates the screen without any data in it.
And it also does not throw any error...
Whenever I put hardcoded data, it works. But that's not what I want.
Here it is my table-component.ts file
import { Component, OnInit } from '#angular/core';
import { ApiService } from '../api.service'
import { MatTableDataSource } from '#angular/material/table';
const COUNTRY_DATA = []
#Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
countryJSON;
displayedColumns: string[] = ['name', 'cases', 'deaths', 'recov', 'permill'];
dataSource = new MatTableDataSource(COUNTRY_DATA);
constructor(private apiService: ApiService) {
}
ngOnInit(): void {
this.apiService.getNews().subscribe((dataJSON) => {
this.countryJSON = dataJSON
for (let countryObject of this.countryJSON) {
COUNTRY_DATA.push
({
name: countryObject.country_name,
cases: countryObject.total_cases,
deaths: countryObject.total_deaths,
recov: countryObject.total_recov,
permill: countryObject.case_per_mill
})
}
console.log(COUNTRY_DATA)
})
}
}
As you can see, I'm printing to the console what does COUNTRY_DATA has in it, and I get the expected data: An array of objects
But they don't populate the Table... And it looks like this:
Well, the main problem with your code is that you don't push your array in the datasource, instead, you're instantiating an empty instance.
if you called dataSource = new MatTableDataSource(COUNTRY_DATA); at the position of console.log(COUNTRY_DATA) it should work.
A better approach when receiving an observable response is to use map instead of a loop, here is an answer for mapping
How to map a response from http.get to a new instance of a typed object in Angular 2
P.S. It will much better if you used an interface to introduce your object, and mapped the result in your ApiService and just set it as the value of your datasource in the component.

Unsure why data isn't passing correctly from child to parent component in Angular 4

I have two components and would like to pass data from the 'child' component that happens when a user has clicked an image from within that component.
I have two components (posting & gifpicker - the child component)
The function applyGif() is the function in the child component that I am using to pass data across - I want to pass this data to the parent component.
Note - the components have some code not required for this aspect removed from view in this post for extra clarity.
The HTML Component below currently shows nothing in the selectedGif for some reason in the view
-- Posting Component (Parent Component) --
/** long list of imports here **/
#Component({
selector: 'app-posting',
templateUrl: './posting.component.html',
styleUrls: ['./posting.component.scss'],
providers: [ GifpickerService ],
})
export class PostingComponent implements OnInit{
public selectedGif: any = '';
#ViewChild(GifpickerComponent) gifpicker: GifpickerComponent;
ngOnInit(): void {
}
constructor(#Inject(DOCUMENT) private document: any,
public gifpickerService: GifpickerService,
) {}
}
-- GifPickerComponent (Child Component) --
import {Component, OnInit} from '#angular/core';
import {FormControl} from '#angular/forms';
import {GifpickerService} from "./gifpicker.service";
#Component({
selector: 'app-gifpicker',
templateUrl: './gifpicker.component.html',
styleUrls: ['./gifpicker.component.scss'],
providers: [ GifpickerService ],
})
export class GifpickerComponent implements OnInit {
public selectedGif: any = {};
constructor(private gifpickerService: GifpickerService) {}
ngOnInit() {
}
applyGif(gif): any {
// this is an json object I want to use/see in the Posting HTML Component
let gifMedia = gif.media[0];
}
}
-- Posting Component HTML (want data from the gifPickerComponent applyGif() shown here --
<div>{{ selectedGif }}</div>
Have you tried using #Output() to pass the information from child to parent after applyGif() method ends.
In your GifPickerComponent declare:
#Output() gifSelected: EventEmitter<any> = new EventEmitter<any>(); // or whatever type your are sending
Once the GIF is selected in applyGif()
applyGif(gif): any {
this.gifPickerVisible = false;
this.uploadedGif = true;
let gifMedia = gif.media[0]; // this is an json object I want to use/see in the Posting HTML Component
this.gifSelected.emit(gifMedia);
}
In the PostingComponent HTML template file where you are using app-gifpicker:
<app-gifpicker (gifSelected)="onGifSelected($event)"></app-gifpicker>
Create onGifSelected in your posting.component.ts file and handle the result:
public onGifSelected(gif: any) {
// Do whatever you need to do.
this.selectedGif = gif;
}
In addition, your posting component is the parent and it hosts other components like your GIFPickerComponent, there is no need to provide the service in both components. It is enough to do it in the parent and it will be passed down to the child component. In other words, the same instance will be passed. With your current arrangement, both parent and child have two different instances of a service.

Angular; Sharing data between this components

I'm new to Angular and I have this problem here:
I want to pass the data that I have from this service+component to another component.
I have a service doing this:
getRecs() {
let recsSub = new Subject<any>();
let recsSubObservable = from(recsSub);
this.socket.on('recs', (recsStatus: any) => {
recsSub.next(recsStatus);
});
return recsSubObservable;
}
Then I have this parent component
private misRecs = null;
snackBarShown = false;
constructor (private appSocketIoService: AppSocketIoService, private snackbar: MatSnackBar) {
let recsObservable = this.appSocketIoService.getRecommendations();
recsObservable.subscribe((recsStatus: any) => {
console.log(recsStatus);
this.misRecs = {};
for(let property in recsStatus.output){
if (recsStatus.output[property]) {
this.misRecs[property] = recsStatus.output[property];
}
};
this.snackbar.openFromComponent (CustomSnackBar, { duration: 5000, });
});
}
What I need is to populate a list in another component with the values obtained from recsStatus but I don't know how to do it.
Thank you all for your help.
If the component is a child component of your component (parent) you describe in the listing you can use the #Input() annotation.
#Component({
selector: 'child-comp',
template: `
<div>
{{ localRecStatus | json }}
</div>
`
})
export class ChildComponent {
#Input()
localRecStatus: [];
}
Now you can use the component in HTML file of your parent component like this:
<child-comp [localRecStatus]="recStatus"></child-comp>
With this, you can use recStatus in your child component. However, recStatus must be a public variable of the parent component. With this technique, you can pass any data to child components. There is also an #Output() annotation you can use in combination with an EventEmitter to send data to the parent component. If the component is not a child, probably a better way is to communicate via a Service between both components.

Dynamic Component in Angular 2

I am trying to implement the tab view component of Prime NG. but my tabs are dynamic in nature ie.
So when the container is loaded it sends multiple AJAX requests for data inside the component.(Maybe the component is initialized multiple times?)
Another thing, in one of the components, moving mouse gives Thousands of errors on the console.
ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
ERROR CONTEXT [object Object]
Not sure why. Used the same component in another place and there was no issue.
Even if I remove the dynamic nature of the components and just place 4 static tabs, everything works perfectly.(Right now the same 4 components are coming from server).
Html Template:
<div class="col-md-12 padding0">
<div class="tabViewWrapper">
<p-tabView (onChange)="handleChange($event)">
<p-tabPanel header="{{tab.tabName}}" *ngFor="let tab of tabs" >
<dynamic-component [componentData]="componentData"></dynamic-component>
</p-tabPanel>
</p-tabView>
<div>
</div>
Component:
#Component({
selector: 'tab-view',
templateUrl: './tab-view.component.html',
styleUrls: ['./tab-view.component.scss'],
encapsulation: ViewEncapsulation.None,
entryComponents: [GenericDataTableComponent, SingleEditCategoryExplorerComponent, AssetsDataTableComponent]
})
export class TabViewComponent implements OnInit {
private ngUnsubscribe: Subject<void> = new Subject<void>();
private componentData = null;
private tabs: Array<any>;
private index:number;
private disabledTabs:Array<any>;
private disabledTabsWhenMetaDataClicked:Array<any>;
versionConfig = {
url: AppSettingProperties.DATA_TABLE_VALUES.VERSIONS_URL,
dateLocale: AppSettingProperties.DATA_TABLE_VALUES.LOCALE,
header: AppSettingProperties.DATA_TABLE_VALUES.VERSIONS_HEADER
};
relatedConfig = {
url: AppSettingProperties.BASEURL + AppSettingProperties.DATA_TABLE_VALUES.RELATED_ENDPOINT,
header: AppSettingProperties.DATA_TABLE_VALUES.RELATED_HEADER
};
constructor(private assetDataLoadedService: AssetDataLoadedService, private assetDetailsService: AssetDetailsService, private assetDetailDataModel:AssetDetailDataModel) { }
#ViewChildren(DynamicContainerComponent) dynamicContainers: QueryList<DynamicContainerComponent>;
ngOnInit() {
this.disabledTabs = [];
//Set items to be disabled when Metadata button is clicked
this.disabledTabsWhenMetaDataClicked = [AppSettingProperties.TAB_RELATEDITEMS, AppSettingProperties.TAB_VERSIONS];
//Disable the tabs as per the condistions
this.disableTabsAsPerRequirement();
//Assigning tabs
this.tabs = this.assetDetailsService.systemTabs;
}
getInitialSelected(tab){
return this.selectedTab == this.tabs.indexOf(tab);
}
get selectedTab():number{
return this.index;
}
set selectedTab(val:number){
this.index = val;
var defaultTab = this.tabs[this.index]['tabName'];
if(!this.assetDetailDataModel.catalogId){
this.assetDataLoadedService.assetDetailPublisher.subscribe(data=>{
this.loadComponentByTab(defaultTab);
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
});
}
else{
this.loadComponentByTab(defaultTab);
}
}
handleChange(e) {
let tabName: string = e.originalEvent.currentTarget.innerText;
this.selectedTab = e.index;
//this.loadComponentByTab(tabName);
}
loadComponentByTab(tabName:string){
switch (tabName) {
case AppSettingProperties.TAB_METADATA:
this.componentData = { component: AssetsDataTableComponent, inputs: {} }
break;
case AppSettingProperties.TAB_CATEGORY:
let categoryConfig: object = {"catalog_id":this.assetDetailDataModel.catalogId,"item_id":this.assetDetailDataModel.assetId};
console.log(categoryConfig);
this.componentData = { component: SingleEditCategoryExplorerComponent, inputs: { tabConfig: categoryConfig } }
break;
case AppSettingProperties.TAB_RELATEDITEMS:
this.componentData = { component: GenericDataTableComponent, inputs: { tabConfig: this.relatedConfig } }
break;
case AppSettingProperties.TAB_VERSIONS:
this.componentData = { component: GenericDataTableComponent, inputs: { tabConfig: this.versionConfig } }
break;
}
}
}
Dynamic Component:
import { Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver } from '#angular/core';
#Component({
selector: 'dynamic-component',
template: `<div #dynamicComponentContainer></div>`,
})
export class DynamicComponent {
private currentComponent = null;
#ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) { }
// component: Class for the component you want to create
// inputs: An object with key/value pairs mapped to input name/input value
#Input() set componentData(data: { component: any, inputs: any }) {
console.log("Building Component Start");
if (!data) {
return;
}
// Inputs need to be in the following format to be resolved properly
let inputProviders = Object.keys(data.inputs).map((inputName) => { return { provide: inputName, useValue: data.inputs[inputName] }; });
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
// We create an injector out of the data we want to pass down and this components injector
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector);
// We create a factory out of the component we want to create
let factory = this.resolver.resolveComponentFactory(data.component);
// We create the component using the factory and the injector
let component = factory.create(injector);
// We insert the component into the dom container
this.dynamicComponentContainer.insert(component.hostView);
// We can destroy the old component is we like by calling destroy
if (this.currentComponent) {
this.currentComponent.destroy();
}
this.currentComponent = component;
console.log("Building Component Finish");
}
}
Another thing is that the console start in dynamic component is shown 8 times.
While console finish is shown 4-5 times.
Seems really weird behavior.
As #echonax wrote in comment.
This is because you are trying to iterate something that is not an array.
Most probably this.tabs.
You can try and write out {{tabs|json}} in a div instead of the *ngFor
Since your response takes sometime to load your DOM will have tabs variable as undefined array.
To solve this initialize the variable to an empty array as below
tabs:Array<any> = []
or inside the constructor as
constructor(){
this.tabs = [];
}

Handle #Input and #Output for dynamically created Component in Angular 2

How to handle/provide #Input and #Output properties for dynamically created Components in Angular 2?
The idea is to dynamically create (in this case) the SubComponent when the createSub method is called. Forks fine, but how do I provide data for the #Input properties in the SubComponent. Also, how to handle/subscribe to the #Output events the SubComponent provides?
Example:
(Both components are in the same NgModule)
AppComponent
#Component({
selector: 'app-root'
})
export class AppComponent {
someData: 'asdfasf'
constructor(private resolver: ComponentFactoryResolver, private location: ViewContainerRef) { }
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
ref.changeDetectorRef.detectChanges();
return ref;
}
onClick() {
// do something
}
}
SubComponent
#Component({
selector: 'app-sub'
})
export class SubComponent {
#Input('data') someData: string;
#Output('onClick') onClick = new EventEmitter();
}
You can easily bind it when you create the component:
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
ref.someData = { data: '123' }; // send data to input
ref.onClick.subscribe( // subscribe to event emitter
(event: any) => {
console.log('click');
}
)
ref.changeDetectorRef.detectChanges();
return ref;
}
Sending data is really straigthforward, just do ref.someData = data where data is the data you wish to send.
Getting data from output is also very easy, since it's an EventEmitter you can simply subscribe to it and the clojure you pass in will execute whenever you emit() a value from the component.
I found the following code to generate components on the fly from a string (angular2 generate component from just a string) and created a compileBoundHtml directive from it that passes along input data (doesn't handle outputs but I think the same strategy would apply so you could modify this):
#Directive({selector: '[compileBoundHtml]', exportAs: 'compileBoundHtmlDirective'})
export class CompileBoundHtmlDirective {
// input must be same as selector so it can be named as property on the DOM element it's on
#Input() compileBoundHtml: string;
#Input() inputs?: {[x: string]: any};
// keep reference to temp component (created below) so it can be garbage collected
protected cmpRef: ComponentRef<any>;
constructor( private vc: ViewContainerRef,
private compiler: Compiler,
private injector: Injector,
private m: NgModuleRef<any>) {
this.cmpRef = undefined;
}
/**
* Compile new temporary component using input string as template,
* and then insert adjacently into directive's viewContainerRef
*/
ngOnChanges() {
class TmpClass {
[x: string]: any;
}
// create component and module temps
const tmpCmp = Component({template: this.compileBoundHtml})(TmpClass);
// note: switch to using annotations here so coverage sees this function
#NgModule({imports: [/*your modules that have directives/components on them need to be passed here, potential for circular references unfortunately*/], declarations: [tmpCmp]})
class TmpModule {};
this.compiler.compileModuleAndAllComponentsAsync(TmpModule)
.then((factories) => {
// create and insert component (from the only compiled component factory) into the container view
const f = factories.componentFactories[0];
this.cmpRef = f.create(this.injector, [], null, this.m);
Object.assign(this.cmpRef.instance, this.inputs);
this.vc.insert(this.cmpRef.hostView);
});
}
/**
* Destroy temporary component when directive is destroyed
*/
ngOnDestroy() {
if (this.cmpRef) {
this.cmpRef.destroy();
}
}
}
The important modification is in the addition of:
Object.assign(this.cmpRef.instance, this.inputs);
Basically, it copies the values you want to be on the new component into the tmp component class so that they can be used in the generated components.
It would be used like:
<div [compileBoundHtml]="someContentThatHasComponentHtmlInIt" [inputs]="{anInput: anInputValue}"></div>
Hopefully this saves someone the massive amount of Googling I had to do.
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length,
ref.instance.model = {Which you like to send}
ref.instance.outPut = (data) =>{ //will get called from from SubComponent}
this.location.parentInjector, []);
ref.changeDetectorRef.detectChanges();
return ref;
}
SubComponent{
public model;
public outPut = <any>{};
constructor(){ console.log("Your input will be seen here",this.model) }
sendDataOnClick(){
this.outPut(inputData)
}
}
If you know the type of the component you want to add i think you can use another approach.
In your app root component html:
<div *ngIf="functionHasCalled">
<app-sub [data]="dataInput" (onClick)="onSubComponentClick()"></app-sub>
</div>
In your app root component typescript:
private functionHasCalled:boolean = false;
private dataInput:string;
onClick(){
//And you can initialize the input property also if you need
this.dataInput = 'asfsdfasdf';
this.functionHasCalled = true;
}
onSubComponentClick(){
}
Providing data for #Input is very easy. You have named your component app-sub and it has a #Input property named data. Providing this data can be done by doing this:
<app-sub [data]="whateverdatayouwant"></app-sub>

Categories