Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngIf for html attribute in Angular2

Tags:

angular

<ion-navbar  hideBackButton >   <ion-title> </ion-title>   ...   ... 

I want hideBackButton to be there conditionally and I don't want to repeat the whole ion-navbar element with *ngIf. Is it possible to to apply *ngIf for hideBackButton attribute?

like image 587
Mark Timothy Avatar asked Mar 07 '16 10:03

Mark Timothy


People also ask

What is the use of * ngIf in angular2?

A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.

How do you use ngIf in HTML?

The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.

Can we use ngIf in P tag?

NgIf is a directive That means, that it can be added to any tag in your template. This includes regular HTML-tags like the "p"-tag shown above and even angular component selectors.

Does ngIf work on Div?

The Angular ngIf directive works essentially as an if statement for HTML, adding this missing feature to the language under the form of the special ngIf attribute. In this example, the container div will only be shown to the user if the user is logged in, otherwise the whole content of the div is not visible.


2 Answers

You have to provide null to boolean values for them to get removed,

<ion-navbar [attr.hideBackButton]="someExpression ? true : null"> 

otherwise angular creates

<ion-navbar hideBackButton="false"> 
like image 140
Günter Zöchbauer Avatar answered Sep 18 '22 08:09

Günter Zöchbauer


You can leverage interpolation:

<ion-navbar [attr.hideBackButton]="someExpression">   <ion-title> </ion-title>   ... ... 

If someExpression is null the attribute won't be present and if someExpression is an empty string, the attribute will be there. Here is a sample:

@Component({   selector: 'my-app',   template: `     <div [attr.hideBackButton]="someExpression">       Test     </div>     <div (click)="toggleAttribute()">Toggle</div>   ` }) export class AppComponent {   constructor() {     this.someExpression = null;   }    toggleAttribute() {     if (this.someExpression==null) {       this.someExpression = '';     } else {       this.someExpression = null;     }   } } 

See this plunkr: https://plnkr.co/edit/LL012UVBZ421iPX4H59p?p=preview

like image 26
Thierry Templier Avatar answered Sep 17 '22 08:09

Thierry Templier