Is there a way for me to steer clear of having to rely on the Elvis Operator?

Throughout my journey building my Angular 2 website, I've found the Elvis Operator to be a crucial element that makes everything possible. It seems like every task I undertake involves mastering how to apply it correctly in every instance where data is involved. If needing a ? on almost everything you do with real data in regular life was normal, I'm sure the Angular documentation would mention it.

For example, when setting up FormGroups for reactive forms following the steps on Angular.io, my form group initially looked like this:

createForm() {
    this.quesForm = this.fbuild.group({
        question: this.featureQuestion.question,
        id      : this.featureQuestion.id,
        name    : this.featureQuestion.name,
        answers : this.fbuild.array([])
    });
    this.setAnswers(this.featureQuestion.answers);
}

get answers(): FormArray {
    return this.quesForm.get('answers') as FormArray;
};

Using the mock-data I created in a const, everything worked fine. But when transitioning to use "real world data," I had to adjust the code as follows after spending several days figuring out the new requirements:

createForm() {
    this.quesForm = this.fbuild.group({
        question: this.featureQuestion ? this.featureQuestion.question: '',
        id      : this.featureQuestion ? this.featureQuestion.id: '',
        name    : this.featureQuestion ? this.featureQuestion.name: '',
        answers : this.fbuild.array([])
    });
    this.setAnswers(this.featureQuestion ? this.featureQuestion.answers: []);
}

It doesn't matter if I'm binding to HTML, attributes, using @Input and @Output, or working within functions; the Elvis Operator always presents itself as the challenge that requires time and effort to solve, even for tasks I thought I already understood. Initially, I believed it might just be a minor issue to resolve, but now I realize it's a significant aspect personally affecting me, suggesting it may not solely be a bug on their end since there isn't more extensive information available. This implies that nobody could effectively use Angular in real-life scenarios without consistently applying this operator throughout the development process, hinting at something I might be overlooking.

Here's an illustration of how I fetch data from Firebase:

Service

export class HomeService {
    BusImage : FirebaseObjectObservable<any>;

    constructor(private af: AngularFire) {}

    getBusImage() {
        this.BusImage = this.af.database.object('/page_area_business_image')
        as FirebaseObjectObservable<any>

        return this.BusImage;
    }
}

Parent Component

export class ExpBusinessComponent implements OnInit {

    private busImageO       : FirebaseObjectObservable<any>;
    private busImageQues01O : FirebaseObjectObservable<any>;
    private busImageQues02O : FirebaseObjectObservable<any>;

    constructor(private _homeService: HomeService) {}

    ngOnInit() {
        this._homeService.getBusImage().subscribe(BusImage => {
            this.busImageO       = BusImage.expand;
            this.busImageQues01O = BusImage.questions.question01;
            this.busImageQues02O = BusImage.questions.question02;
        });
    }
}

Parent Template

<h1>{{busExpInformation?.title}}</h1>
<p>{{busExpInformation?.intro}}</p>

<business-image
    [busImageI]        =  "busImageO"
    [busImageQues01I]  =  "busImageQues01O"
    [busImageQues02I]  =  "busImageQues02O">
</business-image>

Child Component

...

The rest of the provided code has been omitted for brevity. In essence, I've encountered various challenges while working with Angular and applying the Elvis Operator correctly with my data remains crucial for successful outcomes. Despite facing setbacks and unexpected fixes due to database interaction, I strive to align with Angular best practices and suggestions to streamline the development process.

Answer №1

Utilize reactive forms if you enjoy writing a plethora of code that may end up feeling unnecessary.

Otherwise, stick to template driven forms unless there is a particular requirement for using reactive forms.

Answer №2

To avoid the necessity of using ?., you can encompass larger sections with *ngIf so that they may not even reach the point where ?. is needed.

<h1>{{busExpInformation?.title}}</h1>
<p>{{busExpInformation?.intro}}</p>

can be rewritten as

<ng-container *ngIf="busExpInformation">
  <h1>{{busExpInformation.title}}</h1>
  <p>{{busExpInformation.intro}}</p>
</ng-container>

By enclosing your entire component template within an ng-container and including all asynchronously loaded fields with

busExpInformation && a && b && c
, you may never have to use ?. at all.

Another approach is to utilize a resolver to prevent the addition of the component until the data is available (https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically transitioning from a chatbot interface to an Ionic mobile app page as the conversation progresses

My current setup involves incorporating the MS chatbot-framework V3 into my ionic 3 mobile app using Direct line. The goal is to gracefully end the conversation with the chatbot and seamlessly transition to another page within the mobile app, while also p ...

The Ionic 2 application encountering issues with building after the installation of the Facebook login plugin

Currently, I am in the process of developing a Hybrid app using Ionic-2 on Ubuntu. I encountered an issue when trying to add Facebook login functionality to my app. After installing the Facebook plugin, the app build fails. However, if I remove the Faceb ...

What are the steps for utilizing the watch feature in Vue.js with TypeScript?

Currently, I am looking to convert this JavaScript script into TypeScript. However, I require the syntax for watchers. export default { props: ['branch_id'], watch: {} } ...

Enhance your spreadsheet by incorporating dynamic columns utilizing xlsx and sheetjs libraries

I have an array consisting of multiple tags with unique ids and corresponding data: [ { "id": "tagID1", "error": { "code": 0, "success": true }, "data": [ [1604395417575, 108 ...

Guide on showing a placeholder image in Angular2 when the image is missing

I am trying to figure out how to display a default image when the image source coming from the backend is null. Can someone assist me with this issue? If the image part is null, then I want to display the following image: "../assets/images/msg.png" Conso ...

Angular's trio of services tied in a circle of dependency

I'm encountering an issue with my angular project. These warnings keep popping up: WARNING in Circular dependency detected: src\app\core\http\content.service.ts -> src\app\core\http\domain.service.ts -> ...

Tips for setting values to the child component property in Angular 4

When I was using ngif, I encountered an issue with getting the element reference of the child component. After extensive searching, I discovered that in order to access the element, I needed to use view children instead of view child. While I am able to ge ...

Instructions on retrieving keyboard input values from Angular's Material Datepicker using Reactive Forms

Currently, I am using Angular along with material datepicker within Reactive Forms and moment's MomentDateModule. My concern lies in extracting the value that a user types into the form via keyboard input. If you wish to see an example of this scenar ...

How to retrieve start and end time values from dropdown options using formArray in Angular 8

Within my form group, I have start time and end time select options in a form array. My goal is to dynamically update the end time array based on the selected start time. <div [formGroupName]="skillIndex"> Start at: <select ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

Implementing a Typescript directive in AngularJS to create a class

After using AngularJS for quite some time, I decided to explore Typescript. I managed to convert most of my Angular code to Typescript and found it beneficial, especially when working with services. However, I am struggling to convert the following direc ...

Extracting event handlers using @ContentChildren: A guide

I am dealing with a my-button component that needs to be enclosed within a my-button-row component in the following manner: <my-button-row> <my-button [label]="Some Label" (click)="func1($event)"></my-button> <my-button [label ...

(no longer supported) We are unsure about the usage of /deep/, >>>, and ::ng-deep, ::v-deep

Since /deep/ has been deprecated, I have found that using global styles instead is the only viable solution. Does anyone know of an alternative solution where we can still maintain encapsulation or scoped styling? ...

Programmatically initiate form submission in Angular with dynamic status and classes

Presented in a sequential manner, I have various questions within a form that can be navigated forwards and backwards by the user. To make this process smoother, I have incorporated the functionality to use the left and right arrow keys with the help of on ...

The initial load of Angular OpenId Connect triggers the rendering process before the token is fully prepared

I am currently utilizing Angular 10 along with angular-auth-oidc-client (https://github.com/damienbod/angular-auth-oidc-client). My objective is to automatically redirect the user to the authentication server if they are not logged in without displaying a ...

The error message "Undefined is not a function" is being thrown by the $onAuth function in Firebase's AngularFire Authentication

I've been working on updating an application to utilize the latest Firebase Authentication methods. Although most parts are functioning correctly, I encountered an issue while attempting this. myApp.controller('StatusController', function( ...

Issue with page reload in Angular 8 when URL contains a dot

When the URL contains a dot(.) and we attempt to reload the page using the browser's reload function, the following error occurs: The resource you are seeking has been deleted, its name has been changed, or it is currently unavailable. We prefer not ...

Differences Between Angular Event Emitter and Click Listener

I've been delving into Angular by exploring the "Your First App" section on their official website. One aspect that has caught my attention is the event emitter functionality. In the Parent Component (product-list): <app-product-alerts [produc ...

Create a unique custom design for your Mapbox GL control

When developing the website, we utilized Angular 8, Typescript, and SCSS. We are using mgl-map to display a map, and I wanted to create a custom control for it with unique styles. I added the custom control to the map using: const centerOnCoordinatesC ...

Using Angular to assign a CSS variable to the before/after pseudo-classes

Having trouble passing a variable with [ngStyle] and reading it on the ::before class, any guidance in the right direction would be much appreciated! CSS: .handle-slider__control { height: 7px; z-index:1; background: $colour-alto; positi ...