【问题标题】:Pass variable to custom component将变量传递给自定义组件
【发布时间】:2017-07-06 08:27:38
【问题描述】:

我有我的自定义组件:

@Component({
    selector: 'my-custom-component',
    templateUrl: './my-custom-component.html',
    styleUrls: ['./my-custom-component.css']
})
export class MyCustomComponent {
    constructor() {
        console.log('myCustomComponent');
    }
}

我可以这样使用它:

<my-custom-component></my-custom-component>

但是我怎样才能传递一个变量呢?例如:

<my-custom-component custom-title="My Title"></my-custom-component>

并在我的组件代码中使用它?

【问题讨论】:

  • 在组件中使用输入:angular.io/docs/ts/latest/guide/…
  • 请注意:有 4-5 种方法可以做到这一点。在此示例中,这是父/子关系,因此很简单,Input 可以工作。但是,对于没有关系的组件,需要服务,请查看博客文章 fireship.io/lessons/…

标签: angular typescript angular2-template angular2-components


【解决方案1】:

您需要将Input 属性添加到您的组件,然后使用属性绑定将值传递给它:

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

@Component({
    selector: 'my-custom-component',
    templateUrl: './my-custom-component.html',
    styleUrls: ['./my-custom-component.css']
})
export class MyCustomComponent {

    @Input()
    customTitle: string;

    constructor() {
        console.log('myCustomComponent');
    }

    ngOnInit() {
        console.log(this.customTitle);
    }
}

在你的模板中:

<my-custom-component [customTitle]="yourVariable"></my-custom-component>

欲了解更多信息,请查看this page

【讨论】:

  • 这项工作!知道为什么 customTitle 变量在 constructor() 中未定义吗?
  • @rpayam 是 undefined 因为Input 是 Angular 的装饰器,并且在 Angular 的生命周期中“存在”,因此它仅在 OnInit 及之后可用 (constructor 没有任何东西可用于使用 Angular,它在 OnInit 之前初始化)。您可以在此处阅读有关 Angular 生命周期钩子的更多信息:angular.io/docs/ts/latest/guide/lifecycle-hooks.html
  • 但如何访问字符串“myAnotherVariable”? myAnotherVariable
  • 为什么 customTitle 可能是“未定义的”?因为我收到了这个
  • @AnnaLeonenko 也许你用[customTitle]="yourLitteralString"而不是customTitle="yourLitteralString"指定了一个静态值
【解决方案2】:

您可以将@Input() 装饰器添加到组件的属性中。

export class MyCustomComponent {
    constructor() {
        console.log('myCustomComponent');
    }

    @Input() title: string;
}


<my-custom-component title="My Title"></my-custom-component>

或来自变量“theTitle”的绑定标题

<my-custom-component [title]="theTitle"></my-custom-component>

请参阅@Input()decorator 文档。

【讨论】:

  • 顺便说一句,您的 @Input 元素可能需要声明为 public 才能正常工作。
猜你喜欢
  • 2014-01-16
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多