【问题标题】:Angular 2 Pass string argument to componentAngular 2将字符串参数传递给组件
【发布时间】:2017-05-31 09:16:02
【问题描述】:

我的目标是将字符串参数传递给组件。示例:我有一个包含并显示标题和副标题的组件。我想在设置选择器时传递该字符串。比如:

@Component({
    selector: 'title-subtitle',
})

在 html 中:

<title-subtitle title="My title" subtitle="My subtitle"></title-subtitle>

【问题讨论】:

  • 查看此实时 plnk。它可以帮助你plnkr.co/edit/LEtEN9?p=preview
  • 这正是我的答案:p。具体来说,您不能只传递您想要的字符串参数。您可以使用来自 Angular2 的父子通信,它使用 @Input,您可以在其中发送带有其属性的 Object

标签: angular typescript components


【解决方案1】:

使用@input 将字符串从父组件传递到子组件有两种方法。

如果要传递字符串,

<child-component childInput="child input"> </child-component>

如果要将变量从父组件传递到子组件,

<child-component [childInput]="parentInput"> </child-component>

【讨论】:

    【解决方案2】:

    父组件:

    <title-subtitle [childInput]="parentInput">
    </title-subtitle>
    
    private parentInput: any;
    

    ngOnInit() {
        this.parentInput = 'Hello World';
    }
    

    子组件:

    import { Component, Input, OnChanges, OnInit } from '@angular/core';
    
    export class ChildComponent implements OnChanges, OnInit {
      @Input() private childInput: any;
    
      ngOnInit() {
        // When the data is passed instantly, you can access it here.
        // You can also use {{childInput}} in your HTML
        console.log(this.childInput);
      }
    
      ngOnChanges(changes) {
        // When the data is async : get the changes when they are ready
    
        // Get @Input data when it's ready
        if (changes.childInput) {      
           console.log(changes.childInput.currentValue);
        }
      }
    }
    

    注意父 HTML 中属性的命名。

    N.B :当您实际需要对数据执行某些操作时(即深度克隆它,...),您只需要 OnInit 和/或 OnChanges 事件。如果您只在 HTML 中使用插值显示它,则不需要事件。

    NB 2 :请注意,这是发送给您孩子的 SAME OBJECT(相同引用),这意味着如果您在 ChildComponent 中更新对象的属性,更改将也会影响父母。通常你克隆你的对象以避免 OnInit 或 OnChanges 事件中的那种行为。

    【讨论】:

      【解决方案3】:

      如果您查看此 Hero 示例,它应该会回答您的问题

      注意

      <my-hero-detail [hero]="selectedHero"></my-hero-detail>
      

      app.component.ts 文件上

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-03
        • 2017-11-29
        • 2016-01-28
        • 1970-01-01
        • 2017-02-24
        • 2016-03-16
        • 1970-01-01
        相关资源
        最近更新 更多