Angular 2: how to pass attributes to child component? - javascript

In my application I have Home as root component and another generic component named as list which i'm rendering inside Home.
I want to pass data as property to my list component which is coming from XMLHttpRequest.
home.ts
import {Component} from 'angular2/core';
import {DashboardService} from '../../services/dashboard';
import {List} from '../contact/list';
#Component({
selector: 'home',
template:
`
<h3>Home</h3>
<List type="{{type}}"></List>
`
providers: [DashboardService],
directives: [List],
})
export class Home {
private _type: any;
constructor(private _dashboardService: DashboardService) {
this._dashboardService.typeToDisplay()
.subscribe((type) => {
this._type = type;
});
}
}
List.ts
#Component({
selector: 'List',
properties: ['type'],
template: `
<h2>list</h3>
`,
providers: [DashboardService]
})
export class List {
private type: any;
constructor(#Attribute('type') type:string) {
this.type = type;
console.log(type);
}
}
I'm getting string data from typeToDisplay() method its an Http request & assigning to type variable. but when I passed as property to list component I'm getting null in List constructor.
I tried too but i'm getting "type" string same way.
Hope my question is Clear.

This syntax
<List type="{{type}}"></List>
is setting a property not an attribute.
To set an attribute use either
<List attr.type="{{type}}"></List>
or
<List [attr.type]="type"></List>
If you just want to have the value available in List use
#Input() type: any;
instead of the attribute injection.
This way the value is not availabe yet inside the constructor, only in ngOnInit() or later.

Related

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

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");
}
}

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 2 - Get passed object to component via inputs

On my parent page I have a link here:
<a (click)="showPermissionsRates(5757);">Link</a>
The function sets it:
showPermissionsRates(item) {
this.currentEventPoolId = item;
}
With a child component on the parent page here:
<app-event-pools-permissions-rates [eventPoolId]="currentEventPoolId "></app-event-pools-permissions-rates>
And then in my child component TS file I use:
inputs: ['eventPoolId']
But how do I get that value of '5757' in the child component? Such as using alert?
You should be able to just use #Input() on the child property.
I've put this together showing a VERY basic example, but without more to go on regarding your issues, it's hard to know what you need:
https://plnkr.co/edit/y9clOla1WrPFmhMJoz7o?p=preview
The gist is to use #Input() to mark your inputs in the child component, and map those in the template of the parent.
import {Component} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import { ChildComponent } from 'child.component.ts';
#Component({
selector: 'my-app',
template: `
<div>
<button (click)="changeProperty('ABC 123')">Click Me!</button>
<child-component [childProperty]="parentProperty"></child-component>
</div>
`,
})
export class App {
public parentProperty: string = "parentProp";
public changeProperty(newProperty: string) : void {
this.parentProperty = newProperty;
}
}
Then, in the child:
import {Component, Input} from '#angular/core'
#Component({
selector: 'child-component',
template: `
<div>Hello World: {{ childProperty }}</div>
`,
})
export class ChildComponent {
#Input()
childProperty:string;
constructor() {
this.childProperty = 'childProp'
}
}
I think you are setting value to at input variable in a click event, then you have to listen for it in the child component constructor using ngonchanges
ngOnChanges(changes: SimpleChanges) {
if(changes['eventpoolid'] && changes['eventpoolid'].currentValue) {
// you get updated value here
}
}

Angular2 getting data from child route in app-root

In my app-root component I have router-outlet in container with some styles.
I have route:
{
path: 'some-path',
component: ChildContainer,
data: { variable:'variable' },
}
And I can to get variable in ChildContainer, but I need it in AppRoot. So, from documentation I can get it from child, but if I do this in AppRoot constructor:
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
and console.log(root, child) - child is null, and root contains correct child (invoke property getter).
So, how can I get variable in AppRoot?
You may tap into activate event to get reference of instantiated component inside the router outlet.
Check This SO question
#Component({
selector: 'my-app',
template: `<h3 class="title">Basic Angular 2</h3>
<router-outlet (activate)="onActivate($event)" ></router-outlet>
`
})
export class AppComponent {
constructor(){}
onActivate(componentRef){
componentRef.sayhello();
}
}
#Component({
selector: 'my-app',
template: `<h3 class="title">Dashboard</h3>
`
})
export class DashboardComponent {
constructor(){}
sayhello(){
console.log('hello!!');
}
}
Here is the Plunker!!
Update
expose ActivatedRoute as a public property and once you have the routed component reference, subscribe to data,
onActivate(componentRef){
componentRef.route.data.subsribe(data => {
console.log(data);
});
}

#Input() Not Passing As Expected Between Parent-Child Components in Angular 2 App

I am trying to abstract out a tabular-data display to make it a child component that can be loaded into various parent components. I'm doing this to make the overall app "dryer". Before I was using an observable to subscribe to a service and make API calls and then printing directly to each component view (each of which had the tabular layout). Now I want to make the tabular data area a child component, and just bind the results of the observable for each of the parent components. For whatever reason, this is not working as expected.
Here is what I have in the parent component view:
<div class="page-view">
<div class="page-view-left">
<admin-left-panel></admin-left-panel>
</div>
<div class="page-view-right">
<div class="page-content">
<admin-tabs></admin-tabs>
<table-display [records]="records"></table-display>
</div>
</div>
</div>
And the component file looks like this:
import { API } from './../../../data/api.service';
import { AccountService } from './../../../data/account.service';
import { Component, OnInit, Input } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { TableDisplayComponent } from './../table-display/table-display.component';
#Component({
selector: 'account-comp',
templateUrl: 'app/views/account/account.component.html',
styleUrls: ['app/styles/app.styles.css']
})
export class AccountComponent extends TabPage implements OnInit {
private section: string;
records = [];
errorMsg: string;
constructor(private accountService: AccountService,
router: Router,
route: ActivatedRoute) {
}
ngOnInit() {
this.accountService.getAccount()
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);
}
}
Then, in the child component (the one that contains the table-display view), I am including an #Input() for "records" - which is what the result of my observable is assigned to in the parent component. So in the child (table-display) component, I have this:
import { AccountService } from './../../../data/account.service';
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'table-display',
templateUrl: './table-display.component.html',
styleUrls: ['./table-display.component.less']
})
export class TableDisplayComponent {
#Input() records;
constructor() {
}
}
Lastly, here's some of the relevant code from my table-display view:
<tr *ngFor="let record of records; let i = index;">
<td>{{record.name.first}} {{record.name.last}}</td>
<td>{{record.startDate | date:"MM/dd/yy"}}</td>
<td><a class="bluelink" [routerLink]="['/client', record._id ]">{{record.name.first}} {{record.name.last}}</a></td>
When I use it with this configuration, I get "undefined" errors for the "records" properties I'm pulling in via the API/database. I wasn't getting these errors when I had both the table display and the service call within the same component. So all I've done here is abstract out the table-display so I can use it nested within several parent components, rather than having that same table-display show up in full in every parent component that needs it.
What am I missing here? What looks wrong in this configuration?
You need to protect against record being null until it comes in to your child component (and therefore it's view).
Use Elvis operators to protect your template:
<tr *ngFor="let record of records; let i = index;">
<td>{{record?.name?.first}} {{record?.name?.last}}</td>
<td>{{record?.startDate | date:"MM/dd/yy"}}</td>
<td><a class="bluelink" [routerLink]="['/client', record?._id ]"> {{record?.name?.first}} {{record?.name?.last}}</a></td>
You can also assign your input to an empty array to help with this issue:
#Input() records = [];

Categories