ngif stays false, even though its value is right - html

My code looks like this:
component.ts
export class ViewScaleComponent implements OnInit {
private range$: Observable<number>;
constructor(private store: Store<AppState>) {}
ngOnInit() {
this.range$ = this.store.select(x => x.view.range);
}
}
component.html:
<div *ngIf="(range$ | async)">
here {{ range$ | async }}
</div>
The div remains commented in the DOM, an Angular Ghost.
If I remove ngif, the div appears, but the data interpolation fetches nothing (only here and the following whitespace appears).
If in ngOnInit() I do:
this.range$ = this.store.select(x => x.view.range).do(x => console.log(x));
console.log("on init " + this.range$);
then I get:
on init [object Object]
undefined
21
where the last two console logs come from the same line (do()). I wonder whether the first undefined is the reason for not displaying the di.
It's worth noting that sometimes it works(I see the div and the values ofrange$ are being updated as expected).
Any ideas?
PS: I read angular 2 ngIf with observable?, but the observable and async combination look pretty similar to mine.

You dont need the ngIf for this just put {{ range$ | async}}
Update
range:any ;
ngOnInit() {
this.store.select(x => x.view.range).subscribe(x => this.range = x);
}
Template
<div *ngif="range">
here {{ range }}
</div>

Related

Angular Typescript and HTML

I have an interface that looks like this:
export interface GeneralInfo{
Name: string;
Description: string;
}
Later in a component class, I have the following code
export class SignalsComponent implements OnInit {
objGeneral: GeneralInfo;
constructor(private _apiService: APIService)
openPopUp(){
this._apiService.getJsonData().subscribe(
(res => {
var tempJson = JSON.parse(res);
this.objGeneral = tempJson.General as GeneralInfo;
console.log("json --->", this.objGeneral.Description);
}),
(err => { })
);
}
}
When I look at the browser console all works and I see the data I expect to see. However, when I try to invoke the objGeneral.Description property in HTML, it fails. This is my HTML:
<div class="col-lg-6 col-md-6">
{{objGeneral.Description}}
</div>
What am I doing wrong?
Thank you
1) Quick answer
Add a condition to your div :
<div class="col-lg-6 col-md-6" *ngIf="objGeneral">
{{objGeneral.Description}}
</div>
Or use optional chaining if you still want to render an empty div :
<div class="col-lg-6 col-md-6">
{{objGeneral?.Description}}
</div>
Note that you can use optional chaining in condition :
<div class="col-lg-6 col-md-6" *ngIf="objGeneral?.Description">
2) Complete answer
objGeneral is still not defined when your DOM is rendering, it will be defined when the Observable completes. Means you are asking the DOM to render undefined data.
When I look at the browser console all works
Weird, because you should have this type of error in your console which prevents you to call the property of an undefined object :
ERROR TypeError: Cannot read properties of undefined (reading 'Description')
3) Ressources & useful links you might want to check for more information
https://javascript.plainenglish.io/the-beauty-of-optional-chaining-in-typescript-32dd58ce1380
The way you do it is incorrect - objGeneral exists only after async API call. Instead you should deliver this property via async pipe
export class SignalsComponent implements OnInit {
objGeneral$: BehavioutSubject<GeneralInfo> | null;
constructor(private _apiService: APIService)
openPopUp(){
this.objGeneral$ = this._apiService.getJsonData().pipe(
map(res => JSON.parse(res).General as GeneralInfo)
);
}
}
and use it as
<div class="col-lg-6 col-md-6" *ngIf="objGeneral$ | async as objGeneral">
{{objGeneral.Description}}
</div>

Angular 10: how to create dynamic Component / html?

2 questions:
<div>{{ someData }}</div> - how to make {{ someData }} to be converted to html?
<div>{{ MyComponentClass }}</div> - how to make it to create an instance of the component MyComponentClass and put it inside the div?
For question 1 I guess I need a way to get access to the DOM element and then to inject it myself.
For question 2 I have no clue but it'll be so useful.
Question:
You can bind a string/html variable to the [innerHTML] attribute binding.
<div [innerHTML]="theHtmlString"></div>
If the html doesnt work you need to inject the DomSanitizer to tell angular that the html is safe.
constructor(private sanitizer:DomSanitizer) {
this.htmlString = this.sanitizer.bypassSecurityTrustHtml(style);
}
Question:
You can create components dynamically by using a #ViewChild and get the ViewContainerRef from your div and use the componentFactoryResolver:
Template:
<div #yourdiv></div>
Component:
#ViewChild("yourdiv" , {read: ViewContainerRef}) private vcr: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
let resolver = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
let componentFactory = this.vcr.createComponent(resolver);
}

Paginate Observable in HTML with Mat-paginator and Mat-option

I'm using angular material and observables to create an async list with mat-paginator and mat-option (instead of using a table, client requirements). I want to paginate this list in HTML but with the observable stream, not using a subscribe and an assignment to an auxiliary array paginated.
Example:
<mat-option *ngFor="let elem of opMvAsync | async">
<!-- Data printed here -->
</mat-option>
<mat-paginator *ngIf="(opMvAsync | async)?.length > 5" [length]="(opMvAsync | async)?.length" [hidePageSize]="true" [pageSize]="5" (page)="onPageChange($event)"></mat-paginator>
And the TS:
//TS
opMvAsync : Observable<Array<Items>>;
ngOnInit() {
this.opMvAsync = this.service.getItems();
}
I have another example in my app, very similar, but using an auxiliary array :
<!-- HTML-->
<mat-option *ngFor="let elem of lstPaginated">
<!-- Data printed here -->
</mat-option>
<mat-paginator *ngIf="lstOri.length > 5" [length]="lstOri.length" [hidePageSize]="true" [pageSize]="5" (page)="onPageChange($event)"></mat-paginator>
// TS
lstOri: Array<Items>;
lstPaginated: Array<Items>;
ngOnInit() {
this.service.getItems().subscribe(r=> {
this.lstOri= r;
this.lstPaginated= this.lstOri.slice(0, 5);
});
}
onPageChange(event: PageEvent) {
this.lstPaginated= this.lstOri.slice(event.pageIndex * event.pageSize, event.pageIndex * event.pageSize + event.pageSize);
}
This works fine, but it is quite laborious to have to handle two arrays constantly.
Is there any way to work directly paging the observable? Thanks for your advance.
Edit: What I need is to figure it out the way in which I can paginate the observable that I'm rendering in HTML. My OnPageChange should handle which elements of the observable I display, but I don't know how to do it.
You can solve this problem by following below pattern.
In your service, instead of having a method getItems(), create a variable items$. And set its value to the get/post method call.
In your component, set opMvAsync equal to service.items$.
Now in your template, use it with async pipe.
Below is the sample code:
my.service.ts
#Injectable({ providedIn: 'root', })
export class MyService {
...
items$ = this.http.get('some/url/').pipe(...);
...
}
app.component.ts
export class AppComponent {
...
public opMvAsync$ = this.service.items$.pipe(...);
...
}
app.component.html
<div *ngIf="opMvAsync$ | async as opMvAsync">
<mat-option *ngFor="let elem of opMvAsync | async">
<!-- Data printed here -->
</mat-option>
</div>
This way you can avoid the subscribe/unsubcribe work, as async keyword will take care of it.

How to use custom pipes Angular2

I have the following JSON object: http://pastebin.com/1TguvZXc
Here is my Models Component HTML:
<button *ngFor="let category of categories" (click)="chooseCategory(this.category)" type="button" name="button" class="btn btn-default" id="{{category}}">
{{category}}
</button>
<div *ngFor="let model of models?.models">
<div *ngFor="let year of model['years']">
<div *ngFor="let style of year['styles'] | chooseCategory">
{{model.name}}, {{style.submodel.body }}
</div>
</div>
A (pipe?) method from my models.component:
chooseCategory(selectedCategory: string): void {
if((selectedCategory === '')) {
this.filterByPipe.transform(this.models,
['models.years.styles.submodel.body'], selectedCategory);
}
}
Additionally, I would like to use the FilterByPipe pipe from ngx-pipes to filter out by category in models.years.styles.submodel.body.
The code from my HTML roduces the following error:
Unhandled Promise rejection: Template parse errors:
The pipe 'chooseCategory' could not be found ("or="let model of models?.models">
<div *ngFor="let year of model['years']">
<div *ngFor="let s[ERROR ->]tyle of year['styles'] | chooseCategory">
{{model.name}}, {{style.submodel.body }}
I think that you not even read the documentation. Yu should create pipe in this way:
#Pipe({
name: 'somePipe'
})
export class SomePipe {
transform(value: any[]): any[] {
//some transform code...
}
}
and then can you call that in HTML file in this way:
<div *ngFor="let elem of elements | somePipe"></div>
Dont forget to declare your pipe in module.
#NgModule({
declarations: [ SomePipe ]
})
That's what you use is a method, not a pipe.
If you want to executing pipe depend on (f.e.) button click you should build Pipe with argument:
#Pipe({
name: 'somePipe'
})
export class SomePipe {
transform(value: any[], args: any[]): any[] {
let someFlag: boolean = false;
if(args && args[0]) someflag = true;
if(someflag) {
//some transform code...
}
}
}
to call this pipe in this way
<div *ngFor="let elem of elements | somePipe : yesOrNo"></div>
and then can you use in your component method to click button
yesOrNo: boolean = false;
onClickButton(event: any) {
event.preventDefault();
yesOrNo = !yesOrNo;
}
Since you're importing the pipe and calling it from a button in your component, you don't need to call the pipe directly in your component. Also, chooseCategory is just a method, not a pipe. Then, remove the pipe from the following line:
<div *ngFor="let style of year['styles'] | chooseCategory">

How to declare a variable in a template in Angular

I have the following template :
<div>
<span>{{aVariable}}</span>
</div>
and would like to end up with :
<div "let a = aVariable">
<span>{{a}}</span>
</div>
Is there a way to do it ?
Update
We can just create directive like *ngIf and call it *ngVar
ng-var.directive.ts
#Directive({
selector: '[ngVar]',
})
export class VarDirective {
#Input()
set ngVar(context: unknown) {
this.context.$implicit = this.context.ngVar = context;
if (!this.hasView) {
this.vcRef.createEmbeddedView(this.templateRef, this.context);
this.hasView = true;
}
}
private context: {
$implicit: unknown;
ngVar: unknown;
} = {
$implicit: null,
ngVar: null,
};
private hasView: boolean = false;
constructor(
private templateRef: TemplateRef<any>,
private vcRef: ViewContainerRef
) {}
}
with this *ngVar directive we can use the following
<div *ngVar="false as variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="false; let variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="45 as variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="{ x: 4 } as variable">
<span>{{variable | json}}</span>
</div>
Plunker Example Angular4 ngVar
See also
Where does Angular 4 define "as local-var" behavior for *ngIf?
Original answer
Angular v4
div + ngIf + let
{{variable.a}}
{{variable.b}}
div + ngIf + as
view
<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
<span>{{variable.c}}</span>
</div>
component.ts
export class AppComponent {
x = 5;
}
If you don't want to create wrapper like div you can use ng-container
view
<ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
<span>{{variable.c}}</span>
</ng-container>
As #Keith mentioned in comments
this will work in most cases but it is not a general solution since it
relies on variable being truthy
See update for another approach.
You can declare variables in html code by using a template element in Angular 2 or ng-template in Angular 4+.
Templates have a context object whose properties can be assigned to variables using let binding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.
<ng-template #selfie [ngTemplateOutlet]="selfie"
let-a="aVariable" [ngTemplateOutletContext]="{ aVariable: 123 }">
<div>
<span>{{a}}</span>
</div>
</ng-template>
<!-- Output
<div>
<span>123</span>
</div>
-->
You can reduce the amount of code by using the $implicit property of the context object instead of a custom property.
<ng-template #t [ngTemplateOutlet]="t"
let-a [ngTemplateOutletContext]="{ $implicit: 123 }">
<div>
<span>{{a}}</span>
</div>
</ng-template>
The context object can be a literal object or any other binding expression. Other valid examples:
<!-- Use arbitrary binding expressions -->
<ng-template let-sum [ngTemplateOutletContext]="{ $implicit: 1 + 1 }">
<!-- Use pipes -->
<ng-template let-formatPi [ngTemplateOutletContext]="{ $implicit: 3.141592 | number:'3.1-5' }">
<!-- Use the result of a public method of your component -->
<ng-template let-root [ngTemplateOutletContext]="{ $implicit: sqrt(2116) }">
<!--
You can create an alias for a public property of your component:
anotherVariable: number = 123;
-->
<ng-template let-aliased [ngTemplateOutletContext]="{ $implicit: anotherVariable }">
<!--
The entire context object can be bound from a public property:
ctx: { first: number, second: string } = { first: 123, second: "etc" }
-->
<ng-template let-a="first" let-b="second" [ngTemplateOutletContext]="ctx">
Ugly, but:
<div *ngFor="let a of [aVariable]">
<span>{{a}}</span>
</div>
When used with async pipe:
<div *ngFor="let a of [aVariable | async]">
<span>{{a.prop1}}</span>
<span>{{a.prop2}}</span>
</div>
update 3
Issue https://github.com/angular/angular/issues/2451 is fixed in Angular 4.0.0
See also
https://github.com/angular/angular/pull/13297
https://github.com/angular/angular/commit/b4db73d
https://github.com/angular/angular/issues/13061
update 2
This isn't supported.
There are template variables but it's not supported to assign arbitrary values. They can only be used to refer to the elements they are applied to, exported names of directives or components and scope variables for structural directives like ngFor,
See also https://github.com/angular/angular/issues/2451
Update 1
#Directive({
selector: '[var]',
exportAs: 'var'
})
class VarDirective {
#Input() var:any;
}
and initialize it like
<div #aVariable="var" var="abc"></div>
or
<div #aVariable="var" [var]="'abc'"></div>
and use the variable like
<div>{{aVariable.var}}</div>
(not tested)
#aVariable creates a reference to the VarDirective (exportAs: 'var')
var="abc" instantiates the VarDirective and passes the string value "abc" to it's value input.
aVariable.var reads the value assigned to the var directives var input.
I would suggest this: https://medium.com/#AustinMatherne/angular-let-directive-a168d4248138
This directive allow you to write something like:
<div *ngLet="'myVal' as myVar">
<span> {{ myVar }} </span>
</div>
Here is a directive I wrote that expands on the use of the exportAs decorator parameter, and allows you to use a dictionary as a local variable.
import { Directive, Input } from "#angular/core";
#Directive({
selector:"[localVariables]",
exportAs:"localVariables"
})
export class LocalVariables {
#Input("localVariables") set localVariables( struct: any ) {
if ( typeof struct === "object" ) {
for( var variableName in struct ) {
this[variableName] = struct[variableName];
}
}
}
constructor( ) {
}
}
You can use it as follows in a template:
<div #local="localVariables" [localVariables]="{a: 1, b: 2, c: 3+2}">
<span>a = {{local.a}}</span>
<span>b = {{local.b}}</span>
<span>c = {{local.c}}</span>
</div>
Of course #local can be any valid local variable name.
In case if you want to get the response of a function and set it into a variable, you can use it like the following in the template, using ng-container to avoid modifying the template.
<ng-container *ngIf="methodName(parameters) as respObject">
{{respObject.name}}
</ng-container>
And the method in the component can be something like
methodName(parameters: any): any {
return {name: 'Test name'};
}
If you need autocomplete support from within in your templates from the Angular Language Service:
Synchronous:
myVar = { hello: '' };
<ng-container *ngIf="myVar; let var;">
{{var.hello}}
</ng-container>
Using async pipe:
myVar$ = of({ hello: '' });
<ng-container *ngIf="myVar$ | async; let var;">
{{var.hello}}
</ng-container>
A simple solution that worked for my requirement is:
<ng-container *ngIf="lineItem.productType as variable">
{{variable}}
</ng-container>
OR
<ng-container *ngIf="'ANY VALUE' as variable">
{{variable}}
</ng-container>
I am using Angular version: 12. It seems it may work with other version as well.
I liked the approach of creating a directive to do this (good call #yurzui).
I ended up finding a Medium article Angular "let" Directive which explains this problem nicely and proposes a custom let directive which ended up working great for my use case with minimal code changes.
Here's the gist (at the time of posting) with my modifications:
import { Directive, Input, TemplateRef, ViewContainerRef } from '#angular/core'
interface LetContext <T> {
appLet: T | null
}
#Directive({
selector: '[appLet]',
})
export class LetDirective <T> {
private _context: LetContext <T> = { appLet: null }
constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef <LetContext <T> >) {
_viewContainer.createEmbeddedView(_templateRef, this._context)
}
#Input()
set appLet(value: T) {
this._context.appLet = value
}
}
My main changes were:
changing the prefix from 'ng' to 'app' (you should use whatever your app's custom prefix is)
changing appLet: T to appLet: T | null
Not sure why the Angular team hasn't just made an official ngLet directive but whatevs.
Original source code credit goes to #AustinMatherne
For those who decided to use a structural directive as a replacement of *ngIf, keep in mind that the directive context isn't type checked by default. To create a type safe directive ngTemplateContextGuard property should be added, see Typing the directive's context. For example:
import { Directive, Input, TemplateRef, ViewContainerRef } from '#angular/core';
#Directive({
// don't use 'ng' prefix since it's reserved for Angular
selector: '[appVar]',
})
export class VarDirective<T = unknown> {
// https://angular.io/guide/structural-directives#typing-the-directives-context
static ngTemplateContextGuard<T>(dir: VarDirective<T>, ctx: any): ctx is Context<T> {
return true;
}
private context?: Context<T>;
constructor(
private vcRef: ViewContainerRef,
private templateRef: TemplateRef<Context<T>>
) {}
#Input()
set appVar(value: T) {
if (this.context) {
this.context.appVar = value;
} else {
this.context = { appVar: value };
this.vcRef.createEmbeddedView(this.templateRef, this.context);
}
}
}
interface Context<T> {
appVar: T;
}
The directive can be used just like *ngIf, except that it can store false values:
<ng-container *appVar="false as value">{{value}}</ng-container>
<!-- error: User doesn't have `nam` property-->
<ng-container *appVar="user as user">{{user.nam}}</ng-container>
<ng-container *appVar="user$ | async as user">{{user.name}}</ng-container>
The only drawback compared to *ngIf is that Angular Language Service cannot figure out the variable type so there is no code completion in templates. I hope it will be fixed soon.
With Angular 12 :
<div *ngIf="error$ | async as error">
<span class="text-warn">{{error.message}}</span>
</div>
I am using angular 6x and I've ended up by using below snippet.
I've a scenerio where I've to find user from a task object. it contains array of users but I've to pick assigned user.
<ng-container *ngTemplateOutlet="memberTemplate; context:{o: getAssignee(task) }">
</ng-container>
<ng-template #memberTemplate let-user="o">
<ng-container *ngIf="user">
<div class="d-flex flex-row-reverse">
<span class="image-block">
<ngx-avatar placement="left" ngbTooltip="{{user.firstName}} {{user.lastName}}" class="task-assigned" value="28%" [src]="user.googleId" size="32"></ngx-avatar>
</span>
</div>
</ng-container>
</ng-template>
I was trying to do something similar and it looks like this has been fixed in newer versions of angular.
<div *ngIf="things.car; let car">
Nice {{ car }}!
</div>
<!-- Nice Honda! -->
Short answer which help to someone
Template Reference variable often reference to DOM element within a
template.
Also reference to angular or web component and directive.
That means you can easily access the varible anywhere in a template
Declare reference variable using hash symbol(#)
Can able to pass a variable as a parameter on an event
show(lastName: HTMLInputElement){
this.fullName = this.nameInputRef.nativeElement.value + ' ' + lastName.value;
this.ctx.fullName = this.fullName;
}
*However, you can use ViewChild decorator to reference it inside your component.
import {ViewChild, ElementRef} from '#angular/core';
Reference firstNameInput variable inside Component
#ViewChild('firstNameInput') nameInputRef: ElementRef;
After that, you can use this.nameInputRef anywhere inside your Component.
Working with ng-template
In the case of ng-template, it is a little bit different because each template has its own set of input variables.
https://stackblitz.com/edit/angular-2-template-reference-variable
I'm the author of https://www.npmjs.com/package/ng-let
Structural directive for sharing data as local variable into html component template.
Source code:
import { Directive, Input, TemplateRef, ViewContainerRef } from '#angular/core';
interface NgLetContext<T> {
ngLet: T;
$implicit: T;
}
#Directive({
// tslint:disable-next-line: directive-selector
selector: '[ngLet]'
})
export class NgLetDirective<T> {
private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
private hasView: boolean = false;
// eslint-disable-next-line no-unused-vars
constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }
#Input()
set ngLet(value: T) {
this.context.$implicit = this.context.ngLet = value;
if (!this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef, this.context);
this.hasView = true;
}
}
/** #internal */
public static ngLetUseIfTypeGuard: void;
/**
* Assert the correct type of the expression bound to the `NgLet` input within the template.
*
* The presence of this static field is a signal to the Ivy template type check compiler that
* when the `NgLet` structural directive renders its template, the type of the expression bound
* to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
* narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
*/
static ngTemplateGuard_ngLet: 'binding';
/**
* Asserts the correct type of the context for the template that `NgLet` will render.
*
* The presence of this method is a signal to the Ivy template type-check compiler that the
* `NgLet` structural directive renders its template with a specific context type.
*/
static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
return true;
}
}
Usage:
import { Component } from '#angular/core';
import { defer, Observable, timer } from 'rxjs';
#Component({
selector: 'app-root',
template: `
<ng-container *ngLet="timer$ | async as time"> <!-- single subscription -->
<div>
1: {{ time }}
</div>
<div>
2: {{ time }}
</div>
</ng-container>
`,
})
export class AppComponent {
timer$: Observable<number> = defer(() => timer(3000, 1000));
}
Try like this
<ng-container
[ngTemplateOutlet]="foo"
[ngTemplateOutletContext]="{ test: 'Test' }"
></ng-container>
<ng-template #foo let-test="test">
<div>{{ test }}</div>
</ng-template>
original answer by #yurzui won't work startring from Angular 9 due to - strange problem migrating angular 8 app to 9.
However, you can still benefit from ngVar directive by having it and using it like
<ng-template [ngVar]="variable">
your code
</ng-template>
although it could result in IDE warning: "variable is not defined"
It is much simpler, no need for anything additional. In my example I declare variable "open" and then use it.
<mat-accordion class="accord-align" #open>
<mat-expansion-panel hideToggle="true" (opened)="open.value=true" (closed)="open.value=false">
<mat-expansion-panel-header>
<span class="accord-title">Review Policy Summary</span>
<span class="spacer"></span>
<a *ngIf="!open.value" class="f-accent">SHOW</a>
<a *ngIf="open.value" class="f-accent">HIDE</a>
</mat-expansion-panel-header>
<mat-divider></mat-divider>
<!-- Quote Details Component -->
<quote-details [quote]="quote"></quote-details>
</mat-expansion-panel>
</mat-accordion>