其他组件

时间:2016-06-19 02:26:50

标签: angular angular2-components

创建RPG角色创建者。

我有一个NewCharacterComponent,我正在尝试在其中实现DieInputComponent。 NewCharacterComponent从AppComponent路由。代码的重要摘要如下。

我遇到的问题是我没有让DieInputComponent在NewCharacterComponent中加载。当我打破DieInputComponent代码时,控制台中没有抛出任何错误,所以错误很可能是我没有成功导入DieInputComponent但我只是不知道出了什么问题。

新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>

模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() { }
}

模input.component.html

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

2 个答案:

答案 0 :(得分:2)

为了识别您的die-input组件,您需要通过传递给@Component装饰器的配置对象中的directives选项通知Angular它的存在:

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() { }
}

答案 1 :(得分:1)

如果您打算经常使用该组件&amp;在多个组件中,您也可以在main.ts

中提供

provide(PLATFORM_DIRECTIVES, {useValue: <ComponentName>, multi: true})

这实际上将它添加到主指令集合​​中,以便像内置指令一样访问它。

<强> main.ts

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { PLATFORM_DIRECTIVES, provide } from '@angular/core';
import { ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router';
import { AppComponent } from './app.component';
import { DieInputComponent} from './die-input.component';

bootstrap(AppComponent, [
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    provide(PLATFORM_DIRECTIVES, {useValue: DieInputComponent, multi: true}),
]);

新-character.component.ts

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

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

export class NewCharacterComponent {
  constructor() { }
}

新-character.component.html

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