【问题标题】:Angular2 Component Input ChainAngular2 组件输入链
【发布时间】:2016-10-03 17:39:31
【问题描述】:

我想使用 Inputs 制作一个 Angular2 组件链。来自 app > parent > child 的简单示例链。在应用程序中的位置设置了一个数据,该数据在运行时设置在子项中。下面的代码相同。

------------ app.component.ts ---------

import {Component} from 'angular2/core';
import {ParentComponent} from './parent.component';
@Component({
    selector:'componentchain-tag',
    template: `<h1>Level 0</h1>
    <p><parent-tag [fromapp] = "From Level 0" ></parent-tag>
     `,
    directives: [ParentComponent]
}) 
export class AppComponent {
fromapp: string;
}

------------- parent.component.ts ----

import {Component,Input} from 'angular2/core';
import {Child1Component} from './child1.component';
@Component({
    selector:'parent-tag',
    template: `<h1>Level 1</h1>
    <p><child1-tag [child1value] = {{fromapp}} ></child1-tag>
     `,
    directives: [Child1Component]
}) 
export class ParentComponent {
     @Input() fromapp: string;
    child1value: string;
    constructor(){
    }
}

--------------- child1.component.ts ---------

import {Component,Input} from 'angular2/core';

@Component({
    selector: 'child1-tag',
    template: `<h1>Level 3-1</h1>
    This is Child1
    <p>This is variable from {{child1value}}
    `
})
export class Child1Component {
    @Input() child1value: string;

}

在 parent.component.ts 中尝试使用 {{fromapp}},例如保存临时变量等,但它不起作用。我收到错误说parent.component fromapp 未定义。

如何进行组件的多链,它的基础知识对吗?

【问题讨论】:

  • 除非我们创建一个定制的衍生产品,否则不能通过另一个更新 {{fromapp}}。这方面的文献不多。

标签: angular angular2-directives angular2-components


【解决方案1】:

这是无效的

<p><child1-tag [child1value] = {{fromapp}} ></child1-tag>

应该是

<p><child1-tag [child1value]="fromapp"></child1-tag>
  • {{}} 字符串化值
  • {{}} 不能与 []() 或 *xxx 组合(如 *ngFor

【讨论】:

  • 谢谢@günter-zöchbauer,这行得通。除此之外,如果我有第二个子组件。如何从应用程序传递两个值,这些值将由各自的孩子接收。所以在 app.component.ts 里面像这样
  • &lt;parent-tag 让我有点困惑。您使用绑定将数据从父级传递给子级。这看起来像 `
【解决方案2】:

这里有办法解决

  <parent-tag fromappforchild1 = "From Level 0-Child1" fromappforchild2 = "FromLevel 0-Child2" ></parent-tag>

详细文档在这里

https://angular.io/docs/ts/latest/api/core/Input-var.html

还不清楚 parent-tag 里面在做什么,如何控制。例如,在我的 app.component.ts 中,如果我有 templevel0 = "test" ,我根本无法将它放在 parent-tag 中..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-23
    • 2016-12-10
    • 2017-01-16
    • 2016-07-06
    • 1970-01-01
    • 2017-10-18
    • 2017-06-28
    • 2016-09-18
    相关资源
    最近更新 更多