1

创建一个 RPG 角色创建者。

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

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

新字符.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() { }
}

新字符.component.html

<h2>New Character</h2>
<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>
4

2 回答 2

2

为了让你的die-input组件被识别,你需要directives通过传递给 @Component 装饰器的配置对象中的选项来通知 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() { }
}
于 2016-06-19T02:31:50.983 回答
1

如果您要经常在多个组件中使用该组件,您也可以在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}),
]);

新字符.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() { }
}

新字符.component.html

<h2>New Character</h2>
<die-input></die-input>
于 2016-06-19T04:23:18.673 回答