Using the same selector for Angular 2 components

Is there a way to reuse a component selector with the following structure?

@Component({
selector: 'expression-builder',
template: `
    <div class="container">
       <expression *ngFor="#expression of expressions" [prototypes]="prototypes" [expression]="expression" [expressions]="expressions"></expression>
       <a class="btn btn-primary" (click)="addExpression()"><i class="glyphicon glyphicon-plus"></i></a>
    </div>
`,
})

When I try to use this in another component, it doesn't display anything:

@Component({
selector: 'expression',
template: `
<div class="row">
<!-- First Select -->
    <div class="col-xs-3">
        <select class="form-control" [(ngModel)]="selectedPrototypeSelector" (ngModelChange)="onPrototypeChange()">
            <option *ngFor="#p of prototypes" [value]="p.selector">
                {{ p.selectorName }}
            </option>
        </select>
    </div>

<!-- Second Select -->
    <div [ngClass]="{'col-xs-3': prototype?.valueType !== 'Set', 'col-xs-2': prototype?.valueType === 'Set'}" *ngIf="prototype">
        <select class="form-control" [(ngModel)]="expression.constraint">
            <option *ngFor="#constraint of prototype.constraints" [value]="constraint">
                {{ constraint }}
            </option>
        </select>
    </div>

<!-- Third Select -->
    <div [ngClass]="{'col-xs-3': prototype?.valueType !== 'Set', 'col-xs-2': prototype?.valueType === 'Set'}">

       <div>{{expression | json}}</div>
   </div>
    <div class="col-xs-1">
        <a class="btn btn-danger pull-right" (click)="deleteExpression()"><i class="glyphicon glyphicon-remove"></i></a>
    </div>

    <!-- Expression Set selector -->
    <div *ngIf="prototype?.valueType === 'Set'">
       <expression-builder></expression-builder>
    </div>
</div>
`,
directives: [ExpressionBuilderComponent]
})

However, I encounter the error message:

Unexpected directive value 'undefined'

I am looking for a solution to reuse the template specifically when valueType = Set.

Answer №1

When setting this in any element:

<!-- Custom Selector -->
 <div *ngIf="prototype?.valueType === 'Selector'">
     <custom-element></custom-element>
 </div>

You must include the class name of custom-element in the directives attribute of the @Component() to inform angular2 about the directives/components being used in your template.

For example, if the class name of the custom-element is CustomElementComponent and the class name of the parent component is ParentComponent, it should look like this:

parent.component.ts

@Component({
  selector : 'parent',
  template : `
     <div *ngIf="prototype?.valueType === 'Selector'">
         <custom-element></custom-element>
     </div>
  `,
  directives : [
    CustomElementComponent //<-- essential step
  ]
})
export class ParentComponent {

}

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

Issue with implicitly assigning 'any' type to overloaded variadic generic function

We have some code snippets for you to review: export type actions = { abort: () => void; back: () => void; next: () => void; resume: () => void; }; class Sabar { public use<T1>(fn: (arg1: T1, ctx: object, actions: actions) =&g ...

Running Jest tests concurrently causes a TypeError due to converting a circular structure to JSON

While running Jest Tests in parallel, I encountered the following error. Interestingly, when running each test individually or using --RunInBand, they all pass without any issues. Test suite failed to run Jest worker encountered 4 child process except ...

Display a list of items using *ngFor in a dropdown menu without using the optgroup

Is there a way to group data from *ngFor in the dropdown selection without using optGroup? You can find the JSON file link below: JSON Data Typescript Code getProducts() { if (this.products.length < 1) { this.productService.getProducts ...

What is the best approach to upgrade this React Native code from version 0.59.10 to version 0.72.5?

I am encountering an issue with the initialRouteName: 'Notifications' property, while working on my React Native code. Despite trying various solutions, I have not been successful in resolving it. As a newcomer to React Native, any assistance wou ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

When utilizing a personalized Typescript Declaration File, encountering the error message 'Unable to resolve symbol (...)'

I'm having trouble creating a custom TypeScript declaration file for my JavaScript library. Here is a simplified version of the code: App.ts: /// <reference path="types.d.ts" /> MyMethods.doSomething() // error: Cannot resolve symbol "MyMetho ...

Combining the `vuex-typex` npm package's `dist/index.js` for optimal performance with Jest testing framework

I initially raised this question as an open issue on GitHub. My experience with Vue.js, Vuex, TypeScript, and vuex-typex has led me to encounter syntax errors during Jest testing. I am relatively new to working with Vue.js, TypeScript, and Jest. It is wo ...

What is the best way to merge import all with different elements?

My TSLint is flagging the following issue: Multiple imports from 'moment' can be combined into one. Here is the code causing the problem: import * as moment from 'moment'; import { Moment } from 'moment'; I have attempted ...

One issue that may arise is when attempting to use ngOnDestroy in Angular components while rearranging user transitions

Encountered an issue recently with Angular - when the user navigates from component A to component B, component A remains active unless ngOnDestroy is triggered. However, if the user visits component B before going to component A and then leaves, ngOnDes ...

Utilizing Angular Material Autocomplete to showcase a list of employees retrieved from a RestApi by

I need help implementing Angular Material Autocomplete to show only Employee names from the Rest API response that contains an array of employee data like the example below: { "employees": [ { "employeeID&quo ...

Is there a way to retrieve the width of the parent element in ReactJS from a child component?

The issue has been fixed: I forgot to include .current in my ref... I am trying to determine the width of the element that will hold my component. I came across a solution on SO, but unfortunately it did not work for me as it returned undefined: import R ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

Fetching Form Data from Angular Service

My project structure consists of a FATHER component with a stepper, each step-page containing a CHILD component with a FORM. In one page, the CHILD component has another CHILD with yet another FORM. At the final step of the stepper, there is a SUBMIT butt ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Playing a single media object from a group of multiple objects in Ionic

https://i.sstatic.net/VeP0x.png On the screen, there are three Ionic-native media objects available. I have written a code that allows me to play the selected object. play(filename) { this.curr_playing_file = this.createAudioFile(savfilena ...

Applying necessary validation to a checkbox dynamically: Ensuring the checkbox meets necessary criteria

My task involves implementing dynamic form validation using a specific JSON structure. Based on this JSON, I need to dynamically create form fields in a specific format. fields = [ { type: 'text', name: 'firstName', ...

Prevent HTTP method server errors from displaying in the Angular 8 browser console

Currently utilizing Angular 8 and seeking a way to suppress any HTTP errors displaying in the browser console. Here is an example of the error message: zone-evergreen.js:2828 POST http://localhost:3000/api/auth/login 401 (Unauthorized) Within my Error-In ...

In Ionic 2, any modifications made to the data model will only be reflected in the user interface after there is

Q) Why does my data seem to magically appear on the UI after interacting with it, even though I have made changes in the backend? For instance, when fetching and updating data bound to a list, such as: this._LocalStorageService.getClients().then( (data ...