I have a component that I'm using like this in a different component:
<inline-help>
<help-title>{{::'lang.whatIsThis'|i18n}}</help-title>
<help-body i18n="lang.helpBody"></help-body>
</inline-help>
In inline-help I'm using #ViewChild and ng-content to display the help-title and help-body.
#Component({
selector: 'inline-help',
template: `
<div class="inline-help">
<div class="help-icon">
<i class="en-icon-help"></i>
</div>
<div #helptext class="inline-help-text text-left">
<ng-content select="help-title"></ng-content>
<ng-content select="help-body"></ng-content>
</div>
</div>`
})
export class InlineHelpComponent implements AfterViewInit {
#Input() fixed: boolean;
#ViewChild('helptext', {static: false}) text: ElementRef;
......
What I want to do is create a new component like <inline-help-content> that I can use as such inside :
#Component({
selector: 'inline-help',
template: `
<div class="inline-help">
<div class="help-icon">
<i class="en-icon-help"></i>
</div>
<inline-help-content [helpTitle]="something" [helpBody]="something"></inline-help-content>
</div>`
})
But I DONT want to change all the instances of
<inline-help>
<help-title>{{::'lang.whatIsThis'|i18n}}</help-title>
<help-body i18n="lang.helpBody"></help-body>
</inline-help>
that I use in other parts of the codebase, since that's a lot. Is it possible to parse the ViewChild and then get the text inside it and call another component to with the texts as inputs?
In your InlineHelpComponent template, you can wrap the <ng-content>s in elements with template reference variables assigned to them:
<div #helpTitle><ng-content select="help-title"></ng-content></div>
<div #helpBody><ng-content select="help-body"></ng-content></div>
Those template reference variables give you access to the native elements, so you can then pass the innerText properties of those elements into your new InlineHelpContentComponent (just be sure to hide the projected content in InlineHelpComponent so it doesn't display twice). Here's what the InlineHelpComponent template would look like:
<div class="inline-help">
<div style="display:none;">
<div #helpTitle><ng-content select="help-title"></ng-content></div>
<div #helpBody><ng-content select="help-body"></ng-content></div>
</div>
<inline-help-content
*ngIf="showInlineHelpContent"
[helpTitle]="helpTitle.innerText"
[helpBody]="helpBody.innerText">
</inline-help-content>
</div>
Here's a StackBlitz demonstrating this approach.
I found I had to include that *ngIf="showInlineHelpContent" on the inline-help-content component, and set the flag in ngAfterContentInit after a setTimeout, otherwise I was getting an ExpressionChangedAfterItHasBeenCheckedError error.
How can I check with Angular if a DOM element has a class and then add a class to another element?
My Template:
<div class="d-table">
<ui-switch class="d-table-cell">
<span class="switch">
<small></small>
</span>
</ui-switch>
<span class="d-table-cell">
sign in
</span>
</div>
If the span with the class switch has also the class checked, then the color of the text between the span element with the class d-table-cell should be black, otherwise the color should be gray.
No problem with jQuery, but I want to do it the right Angular way :)
.gray {
color:gray;
}
.black {
color: black;
}
<div class="d-table">
<span class="switch" #switch>
<small></small>
</span>
<span class="d-table-cell" [ngClass]="switch.classList.contains('checked') ? 'gray' : 'black'">
sign in
</span>
</div>
We can create template reference variables and can directly access them in the template to get attributes, classes and etc. #switch is a template reference variable
stackblitz
The Angular way would be to avoid, if possible, direct, low-level DOM manipulation. Tie the checked class to some model, and tie the d-table-cell's class to the same model. Like that:
<div class="d-table">
<ui-switch class="d-table-cell" [class.checked]="someVariable">
<span class="switch">
<small></small>
</span>
</ui-switch>
<span class="d-table-cell" [class.active]="someVariable">
sign in
</span>
</div>
and in TS
someVariable: boolean;
Maybe tie someVariable to an ngModel of some input, or whatever logic should dictate whether the switch is checked or not.
step: create a template ref for the main element like this:
HTML:
in the corresponding component:
#ViewChild('switchSpan') switchSpanElement:ElementRef;
After this, you can check the classlist of the said element like this:
if(switchSpanElement:ElementRef.nativeElement.classList.contains('checked')) {
...
}
step: create a boolean variable in the component, that you can access in the template as well (==don't make it private).
isSwitchChecked = false;
and you can make it check whether the class was added when change detecion runs (from this answer, syntax here)
class <yourComponent> implements DoCheck
...
ngDoCheck() {
this.isSwitchChecked = witchSpanElement:ElementRef.nativeElement.classList.contains('checked');
}
you can then bind that boolean variable in the template to add a class to the said span:
<span class="d-table-cell" [ngClass]={'some-class':isSwitchChecked}>
sign in
</span>
and you can define a class in css:
.some-class{
background-color: gray;
}
I'm making simple application, there are 3 components right now, one Parent component, called MAIN COMPONENT, and two child components, one of the child component is displaying selected vehicles and that works fine, but after selection is done I need to click on add button in my app, to open modal (which is another component) where I should choose a customer/client so I could mark that vehicle's are selected customers ownership.
This is how it looks in general:
So basically when add button is clicked (that add button is part of toolbox component) there should be shown modal (another component which holds customers) where I could choose a client.
Component that should shown when add is pressed is: customer.component.html
Now I will post my code:
1.) posting component that should hold clients customer.component.html
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Clients</h4>
</div>
<div class="modal-body item-edit-container">
<h4 class="modal-title" style="text-align: center;">Find client by ID</h4>
<div class="form-group">
<input type="text" class="form-control dash-form-control" id="" placeholder="" autofocus>
<div style="margin-top: 10px;">
<select class="form-control dash-form-control select2" style="width: 100%;">
<option selected disabled>Search for client..</option>
<option>Person 1</option>
<option>Person 2</option>
<option>Person 3</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn save-keyboard-btn" data-dismiss="modal"></button>
</div>
</div>
#Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class ClientComponent implements OnInit {
ngOnInit() {
}
}
I general I've no idea how this should be done, maybe I should place something like this on my main component :
<app-customer></app-customer> and somehow show it when I click on button add, but I really don't know how to achieve this? Could anyone write me some simple steps which I might follow or whatever...
Thanks guys
Cheers
So please keep in mind my question at the end is simple, I need to show a modal which represeting my component when button is clicked..
Thanks
Cheers
as you said it's simple, in the main component for example you add this:
import {Component, OnInit} from'#angular/core';
export class MainComponent implements OnInit{
public shoud_open = false;
openChildComponent(){
this.should_open = true;
}
itemSelected(item){
console.log(item);
}
}
in the html of the MainComponent you add:
<button (click)="openChildComponent()">Open</button>
<div *ngIf="shouldOpen">
<child-component (onItemSelect)="itemSelected($event)" [items]="persons"></child-component>
</div>
now because you are using bootstrap modal, you need to open it programmatically, i assume that you already using JQuery and it's defined somewhere, so in the ChildComponent you do something like this:
import {Component, AfterViewInit, OutPut, Input, EventEmitter} from'#angular/core';
export class ChildComponent implements AfterViewInit{
#OutPut()
public onItemSelect: EventEmitter<any>;
#Input()
public items: Array<any>;
constructor(){
this.onItemSelect= new EventEmitter<any>();
}
ngAfterViewInit(){
$('#modal_id').modal('show');
}
selectItem(item){
this.onItemSelect.emit(item);
}
}
in the html code of ChildComponent you add this:
<select multiple name="items" (change)="selectItem($event)">
<option *ngFor="let item of items" [value]="item">Item</option>
</select>
i didn't test this code, but i'm just giving you example of how you communicate with components, conditionally display them
Developed an reusable directive say CustomerCheckDirective which validates whether the details typed in input is valid or not as below.
#Directive({
selector: '[customerCheck]'
})
export class CustomerCheckDirective implements OnChanges {
#Output()
isValidCustomer: EventEmitter<boolean> = new EventEmitter<boolean>();
....
// method validates and emits based on some logic
{
this.isValidCustomer.emit(false); // can be true or false
}
}
Have developed simple component page with template consuming the above directive.
#Component({
selector: 'validate-customers-demo',
template: `
<validate-page [componentSelector]="'customerCheck'">
<div>
<div class="row">
<div class="form-group" [ngClass]="{'has-error': isValidCustomer }">
<label>Enter customer details</label>
<input class="form-control" customerCheck (isValidCustomer)="setIsValidCustomer($event)" >
<span class="help-block" [hidden]="isValidCustomer"> Not a valid customer </span>
</div>
</div>
...
</validate-page>
`
})
export class CustomerCheckComponent {
isValidCustomer: boolean;
.....
setIsValidCustomer(isValidCustomer: boolean): void {
this.isValidCustomer = isValidCustomer;
}
....
}
But in UI on the page load it below/beside input text field it always show message "Not a valid customer" even on page load. Based on boolean emit of directive the validation message wrapped inside bootstrap's should be shown or hide?.
Note: Initial my approach was use of and it worked.
<i [hidden]="isValidCustomer" style="size:15px;">Not a valid customer</i>
Any help on this?.
Suppose I have a component:
#Component({
selector: 'MyContainer',
template: `
<div class="container">
<!-- some html skipped -->
<ng-content></ng-content>
<span *ngIf="????">Display this if ng-content is empty!</span>
<!-- some html skipped -->
</div>`
})
export class MyContainer {
}
Now, I would like to display some default content if <ng-content> for this component is empty. Is there an easy way to do this without accessing the DOM directly?
Wrap ng-content in an HTML element like a div to get a local reference to it, then bind the ngIf expression to ref.children.length == 0:
template: `<div #ref><ng-content></ng-content></div>
<span *ngIf=" ! ref.children.length">
Display this if ng-content is empty!
</span>`
Updated for Angular 12; old logic ("ref.nativeElement.childNodes.length") gives error, as nativeElement is undefined nowadays.
EDIT 17.03.2020
Pure CSS (2 solutions)
Provides default content if nothing is projected into ng-content.
Possible selectors:
:only-child selector. See this post here: :only-child Selector
This one require less code / markup. Support since IE 9: Can I Use :only-child
:empty selector. Just read further.
Support from IE 9 and partially since IE 7/8: https://caniuse.com/#feat=css-sel3
HTML
<div class="wrapper">
<ng-content select="my-component"></ng-content>
</div>
<div class="default">
This shows something default.
</div>
CSS
.wrapper:not(:empty) + .default {
display: none;
}
In case it's not working
Be aware of, that having at least one whitespace is considered to not beeing empty.
Angular removes whitespace, but just in case if it is not:
<div class="wrapper"><!--
--><ng-content select="my-component"></ng-content><!--
--></div>
or
<div class="wrapper"><ng-content select="my-component"></ng-content></div>
There some missing in #pixelbits answer. We need to check not only children property, because any line breaks or spaces in parent template will cause children element with blank text\linebreaks.
Better to check .innerHTML and .trim() it.
Working example:
<span #ref><ng-content></ng-content></span>
<span *ngIf="!ref.innerHTML.trim()">
Content if empty
</span>
When you inject the content add a reference variable:
<div #content>Some Content</div>
and in your component class get a reference to the injected content with #ContentChild()
#ContentChild('content') content: ElementRef;
so in your component template you can check if the content variable has a value
<div>
<ng-content></ng-content>
<span *ngIf="!content">
Display this if ng-content is empty!
</span>
</div>
If you want to display a default content why dont you just use the 'only-child' selector from css.
https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child
for eg:
HTML
<div>
<ng-content></ng-content>
<div class="default-content">I am default</div>
</div>
css
.default-content:not(:only-child) {
display: none;
}
Inject elementRef: ElementRef and check if elementRef.nativeElement has any children. This might only work with encapsulation: ViewEncapsulation.Native.
Wrap the <ng-content> tag and check if it has children. This doesn't work with encapsulation: ViewEncapsulation.Native.
<div #contentWrapper>
<ng-content></ng-content>
</div>
and check if it has any children
#ViewChild('contentWrapper') contentWrapper;
ngAfterViewInit() {
contentWrapper.nativeElement.childNodes...
}
(not tested)
Sep 2021
There is another technique to accomplish the default content if not provided from the implementation component by using *ngTemplateOutlet directive which allows us to have the customization more control:
Example in source component:
import { Component, ContentChild, TemplateRef } from '#angular/core';
#Component({
selector: 'feature-component',
templateUrl: './feature-component.component.html',
})
export class FeatureComponent {
#ContentChild('customTemplate') customTemplate: TemplateRef<any>;
}
Then in HTML template:
<ng-container
[ngTemplateOutlet]="customTemplate || defaultTemplate"
></ng-container>
<ng-template #defaultTemplate>
<div class="default">
Default content...
</div>
</ng-template>
target component:
<!-- default content -->
<feature-component></feature-component>
<!-- dynamic content -->
<feature-component>
<ng-template #customTemplate>
<div> Custom group items. </div>
</ng-template>
</feature-component>
In my case I have to hide parent of empty ng-content:
<span class="ml-1 wrapper">
<ng-content>
</ng-content>
</span>
Simple css works:
.wrapper {
display: inline-block;
&:empty {
display: none;
}
}
With Angular 10, it has changed slightly. You would use:
<div #ref><ng-content></ng-content></div>
<span *ngIf="ref.children.length == 0">
Display this if ng-content is empty!
</span>
I've implemented a solution by using #ContentChildren decorator, that is somehow similar to #Lerner's answer.
According to docs, this decorator:
Get the QueryList of elements or directives from the content DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.
So the necessary code in the parent component will be:
<app-my-component>
<div #myComponentContent>
This is my component content
</div>
</app-my-component>
In the component class:
#ContentChildren('myComponentContent') content: QueryList<ElementRef>;
Then, in component template:
<div class="container">
<ng-content></ng-content>
<span *ngIf="*ngIf="!content.length""><em>Display this if ng-content is empty!</em></span>
</div>
Full example: https://stackblitz.com/edit/angular-jjjdqb
I've found this solution implemented in angular components, for matSuffix, in the form-field component.
In the situation when the content of the component is injected later on, after the app is initialised, we can also use a reactive implementation, by subscribing to the changes event of the QueryList:
export class MyComponentComponent implements AfterContentInit, OnDestroy {
private _subscription: Subscription;
public hasContent: boolean;
#ContentChildren('myComponentContent') content: QueryList<ElementRef>;
constructor() {}
ngAfterContentInit(): void {
this.hasContent = (this.content.length > 0);
this._subscription = this.content.changes.subscribe(() => {
// do something when content updates
//
this.hasContent = (this.content.length > 0);
});
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}
Full example: https://stackblitz.com/edit/angular-essvnq
<ng-content #ref></ng-content> shows error "ref" is not declared.
The following is working in Angular 11 (Probably 10 also):
<div #ref><ng-content></ng-content></div>
<ng-container *ngIf="!ref.hasChildNodes()">
Default Content
</ng-container>
In Angular 12, the console reports the following for me:
Property 'nativeElement' does not exist on type 'HTMLElement'
There seems to exist a specific attribute childElementCount which you can use for this case.
As a consequence, I used this successfully, which does not wrap the dynamic content into additional elements/tags:
<div class="container">
<!-- some html skipped -->
<ng-container #someContent>
<ng-content></ng-content>
</ng-container>
<span
*ngIf="
someContent.childElementCount === undefined ||
someContent.childElementCount === 0
"
>
Display this if ng-content is empty!
</span>
<!-- some html skipped -->
</div>
in angular 11 I use this and works fine.
template file :
<h3 class="card-label" #titleBlock>
<ng-content select="[title]" ></ng-content>
</h3>
component:
#ViewChild('titleBlock') titleBlock: ElementRef;
hasTitle: boolean;
ngAfterViewInit(): void {
if (this.titleBlock && this.titleBlock.nativeElement.innerHTML.trim().length > 0)
{
this.hasTitle= true;
}
else
{
this.hasTitle= false;
}
}
This solution has worked for me (on angular version 12.0.2).
Note that this will probably not work if your content is dynamic and changes from empty to non-empty (or the other way) after the component was already loaded.
That can be fixed by adding code that changes hasContent inside ngOnChanges.
Example:
import {Component, ViewChild, AfterViewInit} from '#angular/core';
#Component({
selector: 'my-component',
template: '<div [ngClass]="[hasContent ? 'has-content' : 'no-content']">
<span #contentRef>
<ng-content></ng-content>
</span>
</div>']
})
export class Momponent implements AfterViewInit {
#ViewChild('contentRef', {static: false}) contentRef;
hasContent: boolean;
ngAfterViewInit(): void {
setTimeout(() => {
this.hasContent = this.contentRef?.nativeElement?.childNodes?.length > 1;
});
}
}