Using Angular2 to controll CRUD Permissions in HTML with ngIf..else..then

remko de knikker
NYC⚡️DEV
Published in
2 min readAug 16, 2017

I am working on an Ionic2 application that is meant to be a starter application or skeleton for any beginning Ionic2 developer. Code for the starter application with the example below is at my Github repository here.

Instead of creating a separate view, creating and editing pages for an object, I prefer to have a single object detail page in which I control CRUD permissions. To navigate to an object detail page, I create object list pages with a click method for each object item in the object list. In the object list class component, I add an itemSelected(item) method, and either pop an object detail page to the navigation controller’s stack and pass the item object, or I set the root page to the object detail page.

itemSelected(item) {
this.navCtrl.push(Object1DetailPage, { object1: item });
}

Then, in the object detail page, I add a condition with a boolean variable ‘edit’ to decide to display a view block for Read with a Delete action, or an edit block for Create and Update action. This is how I implement my CRUD operations on an object.

Angular2 supports an if-condition via the *ngIf directive, but this originally didn’t allow for the more intuitive ‘if.. else..’ logic.

<div *ngIf=”edit != true”>
<label for=”id”>id</label><input type=”text” name=”id” disabled value=”{{plug.id}}”>
</div>
<div *ngIf=”edit == true”>
EDIT
</div>

Since Angular2 v4, the ngIf directive was extended with an ‘if.. then.. else..’ syntax, in which you can reference the identifier of the HTML tags to include.

<div *ngIf=”edit; then editDiv else viewDiv”>(ignored)</div>
<ng-template #viewDiv>
VIEW
</ng-template>
<ng-template #editDiv>
EDIT
</ng-template>

Another way to control HTML input-tags to be editable or disabled, is to use the [attr.disabled] syntax.

<input [attr.disabled]="edit ? null : true">

When using Ionic2, this translates to the following code.

<ion-input [disabled]="!edit"></ion-input>

In the TypeScript component for the object detail page, I add an ‘edit’ boolean variable.

export class Object1DetailPage { object1: Object = null;
edit: boolean = false;

constructor(public navCtrl: NavController,
public navParams: NavParams) {
this.object1 = navParams.get(“object1”);
this.edit = false;
}
}

See also: NgIf Else lands in Angular 2.x+/4.0, Ashish Singh (Dec 18, 2016)

--

--

remko de knikker
NYC⚡️DEV

Cloud Native Developer Advocate @IBMDeveloper for Cloud Native, Containers, Kubernetes, Security and DevOps. Dutch NYer, dad, humanist with empathy for paradox.