Angular2 Html Templates - html

Is there a way to call a component selector from another html template. For instance:
#Component({
selector: 'reports',
templateUrl: 'reports.html'
})
Can I call that selector "reports" from within another templateUrl? I'm trying to split out my html into separate files in order to make it more manageable. I know how to set it up like <reports></reports> in the html. I'm not sure how I would set this up or call it per say from within the modules.

When you specify a selector, you are basically defining a custom HTML element. So you can use it in any other template in the application as you've shown: <reports></reports>.
Angular modules provide the "template resolution environment". So you need to ensure that the component containing the "reports" selector is declared in the same component as any template that uses it, or is "pulled in" by way of an Angular module import.
I have an example here: https://github.com/DeborahK/Angular2-GettingStarted/tree/master/APM%20-%20Final Check out the star.component.ts.

selector: "[reports]"
selector: "[reports]"

I think your split your html page sub pages, it's very easy.
<body>
<div clss="ui container">
<reports></reports> //the reports page view render hear,just add
this component class in NgModules, it will works
</div>
<div clss="ui container">
<reports-list></reports-list> //you can add another file also same
</div>
</body>

Related

Angular html custom element from typescript [duplicate]

I'm setting HTML returned from the API in my Angular component:
<div [innerHTML]="content"></div>
content in this example is something like this:
<table>
<tr>
<td>[audioPlayer:file.mp3]</td>
</tr>
</table>
Now I would like to inject the actual component inside the table cell.
If I make a certain container, I can create the component with createComponent:
audioPlayerComponentRef: ComponentRef<AudioPlayerComponent>;
#ViewChild('placeholder', { read: ViewContainerRef }) container;
const factory: ComponentFactory<AudioPlayerComponent> =
this.componentFactoryResolver.resolveComponentFactory(AudioPlayerComponent);
this.audioPlayerComponentRef = this.container.createComponent(factory);
Then I can inject it into a container in the template:
<div #placeholder></div>
However, going back to my original goal, I can't use such a container, as the component needs to be injected into a specific position into an innerHtml block.
I've been brainstorming all day, but I can't see any way to achieve this.
Generally speaking, this is contrary to the way Angular works. [innerHTML] is not parsed for any Angular functionality. No component selectors or even a ViewContainerRef can be found there. Rather, even remotely suspicious HTML, CSS and JS is removed as a security measure as Angular only trusts its own templates.
So InnerHTML is a no-go. But I was in the same boat myself and have written a library to solve this exact problem. With it, you can freely load dynamic components into strings without compromising security. If you're still stuck on this, you might wanna have a look at it.

Use styling for ng-content from template component

I've created a template case component which I'm intending to use for multiple cases. To use the component as a template, I used ng-content select="".
It works fine, but not completely as desired. For example:
I have a div with a background image, its style is being configured inside of the template component:
<div class="front-image min-vh-100 min-vw-100" [style.transform]="'scale(' + scale + ')'">
</div>
To make this usable as a template, I replaced the given code with: <ng-content select=".front-image"></ng-content> and used the template inside of another component like this:
<app-case-template *ngIf="cases[3] as case">
<div class="front-image min-vh-100 min-vw-100" [ngStyle]="{ 'background-image': 'url(' + case.image + ')'}"
[style.transform]="'scale(' + scale + ')'">
</div>
</app-case-template>
How can I achieve the template to always get its styling from the template component - right now I had to declare its styling inside of the new component to get it working. Additionally [style.transform] stopped working.
Is there something like a bypass?
You may be going about this the wrong way. I'll try to outline a good way to do it. First, have a directory for your templates:
templates
- template.component.css (generic styling)
- template.component.html (your markup)
- template.component.ts (your ts/js)
Set up your template.ts for use:
import {Component} from '#angular/core';
#Component({
selector: 'template-component',
templateUrl: 'template.component.html'
styleUrls: ['./template.component.css']
})
export class TemplateComponent {
}
Register it in your component.module.ts (or whatever you may have called it):
...
import {TemplateComonent} from './templates/template.component';
...
const exportedComponents = [
SvgIconComponent
]
If needed, have your shared.module.ts export it:
import {ComponentsModule} from './components/components.module';
...
exports: [ComponentsModule]
Now you can use it like it's a custom HTML tag (your selector):
<template-component class="template"> </template-component>
Now it will always grab the css styling from itself, but you can stick a custom class in that tag as I have done, or call it like this from your main component's style page:
template-component {
margin: 10px;
background-color: grey;
}
There's a lot you can do including setting #Input() tags in your template that can be called from your HTML tag. You can also use Angular bindings to dynamically enter values or text into it. Many options here.
Note: instead of calling them templates, consider calling them shared components, or shared modals (if so). Have a directory called shared > components and have a custom-name directory with the like in there for organization.

Create a master table component and add child columns dynamically in angular

Good morning everyone !
So have to create an application that displays many tables that all look the same (except their columns of course and the objects inside).
I have a master table component which can be summarized by:
<master-table>
<!-- here I define the master table style, pagination, etc etc
which is the same everywhere -->
</master-table>
In the master table component TS file I have basically options that are relevant for every page where this kind of table should be displayed, such as filterDate, clearSelection etc etc etc nothing very special.
The point is, I don't want to repeat this code every where because it is not necessary, so my idea was to create several component that would extend the master table component.
It works fine for the typescript values, but I am stuck with the HTML.
In my master table HTML I would like at some point some kind of placeholder something like this:
<master-table>
<standard-for-all-table></standard-for-all-table>
<!-- insert here child columns -->
</master-table>
In the components that extends my master table I was imagining then something like:
<!-- child component -->
<master-table></master-table>
<child-column>column definition</child-column>
Doing this would allow me to define only the columns in the child components HTML and they would be added automatically to the parent HTML at runtime...
Any idea how to do this ?
Cheers and thanks !
Basically you have to create your main master-table component and your generic list chid-column component and insert it in your parent html template structure.
I've edit the final part hope in a better understanding way...
Then you can structure your child component to contain all the properties you need and thanks to *ngIf show only the properties you return from your provider methods i.e. getClients(), getUsers(), getHouses(), also thanks to the #Input decorator you can inject this data directly from the parent to the child and create many components you want with just a change of the data.
So in your parent you can have something like
import { Component } from '#angular/core';
import { MY_DATA_FROMP_ROVIDER } from './mydata/provider';
#Component({
selector: 'master-table',
template: `
<ul>
<child-column *ngFor="let item of items"
[item]="item">
</app-hero-child>
</ul>
`
})
export class MasterTableComponent {
items:any
constructor(public data: MYDATAFROMPROVIDER) {
this.items = MYDATAFROMPROVIDER.myGetMethod();
}
And in your child
import { Component, Input } from '#angular/core';
import { INTERFACE } from './mydata/interface';
#Component({
selector: 'child-column',
template: `
<div *ngIf="item.id">{{item.id}}</div>
<div *ngIf="item.name">{{item.name}}</div>
<div *ngIf="item.address">{{item.address}}</div>
<div *ngIf="item.phone">{{item.phone}}</div>
`
})
export class ChildColumnComponent {
#Input() item: INTERFACE;
}
If you want to go deeper: Component Interaction
This guide is from official angular page Here
Here is the live sample of it
Not sure if these links could help.
But I actually worked on a project where we want to dynamically loading Child component into a Grid(Parent component).
And later on we can pass any component with different view inside the Grid
Guess that pretty close to your goal.

Angular4 ng-content gets built when ngIf is false

I have a problem with the new ng-content transclusion.
Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).
I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).
<ng-content></ng-content>
If I set the surroundings up like this, the log statement doesn't show:
<my-wrapper *ngIf="false">
<my-component></my-component>
</my-wrapper>
I assume, the my-wrapper component does not get built, so the content is ignored.
But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):
<ng-container *ngIf="false">
<ng-content></ng-content>
</ng-container>
I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.
The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.
overview.html:
<ng-container *ngFor="let item of items">
<my-wrapper>
<my-component id="item.id"></my-component>
</my-wrapper>
</ng-container>
my-wrapper.component.html:
<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail">
<ng-content></ng-content>
</div>
Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.
Based on the comment of #nsinreal I found an answer. I find it to be a bit abstruse, so I'm trying to post it here:
The answer is to work with ng-template and *ngTemplateOutlet.
In the my-wrapper component, set up the template like this (my-wrapper.component.html):
<div (click)="toggleDetail()">Click for more</div>
<div *ngIf="showDetail" [hidden]="!isInitialized">
<ng-container *ngTemplateOutlet="detailRef"></ng-container>
</div>
Note, that the [hidden] there is not really necessary, it hides the "raw" template of the child until it decides it is done loading. Just make sure, not to put it in a *ngIf, otherwise the *ngTemplateOutlet will never get triggered, leading to nothing happening at all.
To set the detailRef, put this in the component code (my-wrapper.component.ts):
import { ContentChild, TemplateRef } from '#angular/core';
#Component({ ... })
export class MyWrapperComponent {
#ContentChild(TemplateRef) detailRef;
...
}
Now, you can use the wrapper like this:
<my-wrapper>
<ng-template>
<my-component></my-component>
</ng-template>
</my-wrapper>
I am not sure, why it needs such complicated "workarounds", when it used to be so easy to do this in AngularJS.
By doing this:
<my-wrapper *ngIf="false">
<my-component></my-component>
</my-wrapper>
You are not calling MyComponent component, because the *ngIf is false. that means, that not calling it you are not instancing it and, therefore, not passing through its ngOnInit. And that's why you are not getting the console log.
By doing this:
<ng-container *ngIf="false">
<ng-content></ng-content>
</ng-container>
You are inside the component, you are just limiting what to render in your template, but you already instanced your component and, therefore, you passed through your ngOnInit and you get your console log done.
If, you want to limit something (component call with selector or a ng-content or even a div) until you have some data available, you can do the following:
datasLoaded: Promise<boolean>;
this.getData().subscribe(
(data) => {
this.datasLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
}
);
And in your template:
<ng-container *ngIf="datasLoaded | async">
// stuff here
</ng-container>
Or:
<my-component *ngIf="datasLoaded | async">
// Didn't test this one, but should follow the same logic. If it doesn't, wrap it and add the ngIf to the wrapper
</my-component>
It’s because Ng content happens at the build time and when you pass the content it is actually not removed or recreated with the ngIf directive. It is only moved and the component is instantiated .
I encountered this problem recently as well but settled on a different solution than the currently accepted one.
Solution (TL;DR)
(Solution is for AngularDart; I figure it's similar in Angular though)
Use a structural directive; tutorials linked below.
Instead of:
<my-wrapper>
<my-contents></my-contents>
</my-wrapper>
your usage becomes:
<div *myWrapper>
<my-contents></my-contents>
</div>
which is shorthand for the following (in AngularDart; I think Angular uses <ng-template>)
<template myWrapper>
<div>
<my-contents></my-contents>
</div>
</template>
The MyWrapper directive logic is similar to NgIf except it has its own logic to compute the condition. Both of the following tutorials explain how to create an NgIf-like directive and how to pass it your own inputs using the special microsyntax (e.g. *myWrapper="myInput: expression"). Note that the microsyntax doesn't support outputs (#Output), but you can mimic an output by using an input that is a function.
Tutorial for Angular
Tutorial for AngularDart
Caveat: Since this is just a directive, it shouldn't do anything more complicated than instantiating a template ref at the appropriate time and maybe specifying some DI providers. For example, I would avoid trying to apply styles or instantiating a complex tree of components in the directive. If I wanted to create a list component, I would probably take the #ContentChild(TemplateRef) approach described in another answer; you would lose the asterisk shorthand for creating <template> but you would gain the full power of components.
My problem
My team owns an app that's part of a larger web application with other apps owned by other teams. Our components assume they can inject a MyAppConfiguration object, but this object can only be injected after it is loaded with an asynchronous request. In our app this is not a problem: we have a "shell" component that hides everything behind an ngIf until the configuration is loaded.
The problem is when other teams want to reference our components. We don't want them to duplicate the "wait until configuration is loaded" logic every time, so I tried creating a wrapper component that can be used like so:
<my-app-wrapper>
<my-app-component></my-app-component>
</my-app-wrapper>
The wrapper injects a service object and hides its contents behind an ngIf until the service says that the configuration is loaded.
Like the question poster, I discovered that the ng-content approach doesn't work as intended: while the contents are correctly hidden from the DOM, Angular still instantiates the components causing dependency injection to fail.
The solution that I settled on was to rewrite the wrapper component as a structural directive.

Does an Angular 2 '#Component' decorator always need an element name selector?

In this example, from the official Angular 2 docs, the decorator looks like this:
#Component({
selector: 'my-app',
template: '<h1>My First Angular App</h1>'
})
Example: would prefer not not have my HTML code littered with non-standard elements, and would prefer something like (NB: ng-angular is only an example I would like to see):
import { Component } from '#angular/core';
#Component({
template: '<h1>Wait! Bloody wait some more.</h1>'
})
export class ListComponent { }
and used something like this:
<div ng-component="List"</div>
Or is the a Component decorator like this used only when you want to create a new HTML element, and then stick to a plain Listcontroller for the div in my example above?
A selector is not always needed eg. you have a top component of a module that is loaded by router and displayed in
selector is needed for any other type of component. otherwise angular wouldn't know what component it should render.
I haven't heard about attribute "ng-component"
[EDIT]
kit effectively answered correctly in his/her first comment:
You have to create an element that would enclose your template however it doesn't have to be a new HTML element because selector can be a element, [attribute] or class, eg.
<div test>
could be an element for component with selector: '[test]'
A component is a new HTML element, something like <my-component>Hello</my-component>.
I think what you want is a directive.
An Attribute directive changes the appearance or behavior of a DOM element.
So you can do something like <div makeItBlue>Blue stuff</div>
Just to elaborate: The selector can be a standard CSS-selector, so your HTML can be non-angular-centric.
Example:
#Component({
selector: 'div.player-list',
...
})
export class PlayerList {
}
will match <div class="player-list and-possibly-some-other-classes">...</div> (i.e. replacing the div with your angular template)