Search code examples
angularangular2-components

Angular 2 component inside other component


Creating an RPG character creator.

I have a NewCharacterComponent and I am trying to implement a DieInputComponent inside it. The NewCharacterComponent is routed from an AppComponent. Important snippets of the code will be below.

The issue I am running into is that I am not getting the DieInputComponent to load within the NewCharacterComponent. When I break the DieInputComponent code no errors are thrown in the console, so the error is likely that I am just not successfully importing the DieInputComponent but I just have no idea what is going wrong.

new-character.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router-deprecated';

import { DieInputComponent } from './die-input.component';

@Component({
  selector: 'core-worlds',
  templateUrl: 'app/new-character.component.html',
  styleUrls: ['app/new-character.component.css'],
})

export class NewCharacterComponent {
  constructor() { }
}

new-character.component.html

<h2>New Character</h2>
<die-input></die-input>

die-input.component.ts

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

@Component({
    selector: 'die-input',
    templateUrl: 'app/die-input.component.html',
    styleUrls: ['app/die-input.component.css'],
})

export class DieInputComponent {
    constructor() { }
}

die-input.component.html

<input type="number" placeholder="1d4"></input>

Solution

  • In order to have your die-input component recognized, you'll need to inform Angular about its existence, through the directives option in the configuration object passed to the @Component decorator:

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router-deprecated';
    
    import { DieInputComponent } from './die-input.component';
    
    @Component({
      selector: 'core-worlds',
      templateUrl: 'app/new-character.component.html',
      styleUrls: ['app/new-character.component.css'],
      directives: [ DieInputComponent ] //<<<< Where the magic happens
    })
    
    export class NewCharacterComponent {
      constructor() { }
    }