Troubleshooting: Inability of Angular2 Component to access class property within template

Here is the code snippet that I am currently working with: post.component.ts:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { JobsService } from '../jobs.service';

@Component({
  selector: 'job-post',
  templateUrl: './create.template.html',
  providers: [JobsService]
})

export class JobPostComponent {
  job: any = {};
  errorMessage: String;

  constructor(private _router:Router, private _jobsService:JobsService) {}

  create() {
    this._jobsService
      .create(this.job)
      .subscribe(createdJob => this._router.navigate(['/jobs', createdJob._id]), error => this.errorMessage = error);
  }
}

create.template.html

<h1>Post New Job</h1>
<form (ngSubmit)="create()" novalidate>
  <div class="form-group">
    <label for="isExtensible">Is Extensible</label>
    <input type="checkbox" required [(ngModel)]="job.isExtensible" name="isExtensible" id="isExtensible">
  </div>
  <div class="form-group">
    <label class="form-control-label" for="isOpenEnded">Open Ended</label>
    <input type="checkbox" required [(ngModel)]="job.isOpenEnded" name="isOpenEnded" id="isOpenEnded">
  </div>
  <div class="form-group">
    <contract-type></contract-type>
  </div>
</form>

Additionally, there is another component called contract-type.component.ts

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'contract-type',
  template: `
    <div *ngIf="contractTypes">
      <label class="form-control-label" for="contractType">Contract Type</label>
      <select id="contractType" name="contractType" required [(ngModel)]="job.contractType" class="form-control">
         <option value="0">Select an item</option>
         <option *ngFor="let contractType of contractTypes" value="contractType.name_en">{{ contractType.name_en }}</option>
       </select>
    </div>
    `
})

export class ContractTypeComponent {
  private contractTypes;
  constructor(private _http: Http) {
    this._http.get('/api/contractTypes')
      .subscribe(res => {
         this.contractTypes = res.json();
         console.log(this.contractTypes)
      });
  }
}

The console output can be viewed here: https://i.sstatic.net/ydyBn.png. However, when viewing it on the browser, the dropdown list does not appear. Removing the *ngIf directive from the div results in an error stating

cannot read property <contractTypes> of undefined
. My goal is to have a dropdown list populated from an API response inside the create.template.html.

Answer №1

To create interaction between your components, follow these steps: In your parent component 'create.template.html':

<contract-type [job]="job"></contract-type>

Within your conract-type.component.ts file: Start by importing Input: import { Component, Input} from '@angular/core'; Then update your component class as shown below:

export class ContractTypeComponent {
  private contractTypes;
  @Input() job;
  constructor(private _http: Http) {
    this._http.get('/api/contractTypes')
     .subscribe((res)=>{
       this.contractTypes = res.json();
       console.log(this.contractTypes)
    });
  }
}

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

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

Issue with fuse-box: unable to import ReactDOM

Recently, I decided to switch from webpack to fuse-box for my side project. Everything is compiling without any issues, but when I try to load it, an error pops up: I downloaded a React demo code and it works fine. Additionally, there are no problems wit ...

What is the best way to retrieve the value of the first name using Protractor?

Is there a way to store the value of the first name using a protractor script? The first name is set when the user logs in and corresponds to the name of the logged-in user. I am wondering if this can be done utilizing by.addLocator(). Here is the tag tha ...

Is nesting ajax calls in jQuery a clever strategy?

I currently have this ajax call: $.ajax({ url: "misc/sendPM.php", type: "POST", data: data, success: function(stuff) { if (typeof stuff == "object") { var err = confirm(stuff.error); if (err) { ...

Difficulty rendering wireframe with Three.js MeshBasicMaterial

I am experiencing an issue with my geometry created using the three.js API. When I export an obj file from Blender and import it, the object renders faces instead of wireframe as desired. Could this problem be due to a mistake in my import or export proces ...

Retrieve an Excel file using Selenium through a URL, but only obtain JavaScript code instead

I am attempting to download an Excel file using its URL, but all I receive is JavaScript code. I'm unsure of how to retrieve the actual file instead of just the JS code. Here is my current code: # -*- coding: utf-8 -*- from selenium import webdrive ...

Can one button be clicked to trigger the activation of another button through a click?

Just as the title suggests, I am wondering how to make this happen? Any guidance would be greatly appreciated! $('.notVisible').click (function(){ alert("I'm the invisible button") }); $('.visible').click (function(){ al ...

What is the best way to access the type of a generic property within a type?

type Mother = { action<X>(alpha: X, bravo: string):void } type ChildArguments = Parameters<Mother['action']<number>> // encountered an issue Assuming the aforementioned code is functioning properly, I will be able to execut ...

Unveiling the significance behind the utilization of the.reduce() function in conjunction with Object.assign()

After consulting the method/object definitions on MDN, I am attempting to create a simplified step-by-step explanation of how the script below (referenced from a previous post) is functioning. This will not only aid in my understanding but also help me ada ...

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

How to retrieve the IP address of a client using Node.js within a setInterval loop

Working on a project utilizing nodejs to fetch client IP Addresses. Within the setinterval function, I have set up the following code: var countdown2 = setInterval(function(){ async function baked(req, res, id){ var getIP = req.headers['x-forward ...

Styled-components does not generate a style tag as output

After creating a new project in React with Webpack, I decided to experiment with Styled Components. In my index.js file, the code is structured like this: import React from "react" import ReactDOM from "react-dom" import Page from "./site/Page" import s ...

"Introducing the new Next.Js 14 sidebar featuring a sleek hamburger menu

I am in the process of developing a chat application. Currently, I have a sidebar that displays existing conversations and I would like to make it responsive by implementing open and close functionalities for mobile devices. Here is the code snippet for m ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

Creating numerous pre-signed URLs using an Application Programming Interface

An API has been developed to generate pre-signed URLs for files stored in a private S3 bucket. The goal is to store these URLs in an array for access from another application. ["FILE1 pre-signed URL", "FILE2 pre-signed URL", etc..] However, there seems to ...

How can I use an HTML button to activate a function that inserts text into a read-only text-box?

Trying to write a simple piece of HTML code that finds the number greater than or equal to the first initial amount that wholly divides the second given amount. The code attempts to divide the numbers, and if it fails, increments the first number by 1 and ...

Navigate using an abstract data type

I am looking to transmit abstract data (In Angular 4 or 5) from one component to another without it being visible in the url. Currently, I am using the following method: let navigationExtras: NavigationExtras = { queryParams: { "firstname": "Nic ...

Build failure encountered with create-react-app due to protracted duration followed by an error notification

When I created a react project version 15 and ran npm run build, it took an unusually long time (20 mins) and appeared to be frozen. Eventually, I encountered the following error. How can I resolve this issue? enter code heresers/rice/my-app-2/node_modu ...

Angular JS has blocked the cross-origin request from $http

I have been working on implementing search suggestion functionality using a Suggestions API "". The implementation works fine with Ajax GET requests, but when I try to use it with Angular's $http service, I encounter an error in the console: Cross-Or ...

Leveraging jQuery functions with dynamically generated DOM elements in JavaScript

On my website, I have a button that dynamically generates a dropdown menu, a textfield, and two buttons when clicked. The purpose of the textfield is to track the quantity selected, while the two buttons allow users to increase or decrease the value by 1. ...