在@component下为Declaratives分配组件会引发编译错误

时间:2017-11-24 20:46:31

标签: angular angularjs-directive

不确定为什么组件不能分配给@component的declaratives属性。父语句中的此语句(指令:[ChildComponent] )会引发编译错误。我的代码目的是将数据值从父传递给子。我听说使用RC6声明并不起作用,所以我在ngModule的声明中声明了子组件,并且编译错误已经解决,但无法在子视图中获取数据。

Parent component:
import { Component } from '@angular/core';
import {ChildComponent} from './child-input.component'

@Component({
  selector: 'app-root',
  template: `
  <h1>parent here!</h1>
  <child-component [child] = 'parent'></child-component>
  `,
  styleUrls: ['./app.component.css'],
  directives: [ChildComponent]
})
export class AppComponent {
  parent = 'parent to child';

}


child component:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'child-component',
  template: '<h1>{{child}}</h1>'
})
export class ChildComponent {
  @Input() child : string;

}

以下是我的CLI版本详细信息:

@angular/cli: 1.4.8
node: 6.11.2
os: win32 x64
@angular/animations: 4.4.6
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.8
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.3.4

由于 Yesp

2 个答案:

答案 0 :(得分:0)

“我在ngModule的声明中声明了子组件,并且编译错误已解决,但无法在子视图中获取数据”

这是因为如果你想将一个字符串传递给子组件,你应该像[child] = "'parent'"一样传递它,而不仅仅是'parent'

<child-component [child]="'parent'"></child-component>

答案 1 :(得分:0)

您要做的是在父组件中使用子组件。这与指令无关,它们用于不同的目的(structural directiveshttps://docs.google.com/spreadsheets/d/1inmd2Lc1aOfVL7POKye6p2OQHsloJryISgdqNMowW90/edit?usp=sharing)。不幸的是,您试图在 [directives] 属性中将其声明为此类指令,并且编译器不喜欢这样。所以请注意,指令!= 声明。这是编译器可能不喜欢的行:

directives: [ChildComponent]

在另一个组件中使用组件的常用方法是在模块中声明它。如果两个组件都在同一个模块(或文件夹,我不确定那个),他们彼此了解并且可以在彼此内部使用,不需要在组件内部声明它们。

我目前还不确定为什么你的值在子组件中没有正确设置,代码本身看起来是正确的。它在浏览器中显示的是什么?它是否显示不同的文本,是否包含子组件及其内容,或者 h1 标记是否为空?