2016-06-19 77 views
0

創建RPG角色創建者。其他組件內的角度2組件

我有一個NewCharacterComponent,我試圖在它內部實現一個DieInputComponent。 NewCharacterComponent從AppComponent路由。代碼的重要代碼片段如下。

我遇到的問題是,我沒有得到在NewCharacterComponent中加載DieInputComponent。當我打破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() { } 
} 

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

模輸入。 component.html

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

回答

1

爲了讓您的die-input部分予以確認,你需要告知角知道它的存在,通過傳遞給@Component裝飾的配置對象的directives選項:

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

真棒,這WOR糟透了。我已經完成了Tour of Heroes教程,但我不認爲我已經真正掌握了指令實際上做了什麼。 – Crimthann

+0

可悲的是,現在已經失去了根據,我們現在必須在我們的模塊中使用一個聲明 –

0

如果你要通常在多個組件中使用組件&,您也可以在您的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>