Html 将参数传递给 Angular2 组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41926598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:19:47  来源:igfitidea点击:

Passing Parameter to Angular2 Component

htmlangular

提问by Fearghal

I'm Learning Angular2 so be gentle... I have a basic Component which has a string array. I want to pass an integer to this component and have it return the string found at the index of that parameter.

我正在学习 Angular2 所以要温柔......我有一个基本的组件,它有一个字符串数组。我想将一个整数传递给这个组件,并让它返回在该参数的索引处找到的字符串。

E.g. myComponent[number]=1 returns string "second element".

例如 myComponent[number]=1 返回字符串“第二个元素”。

My code so far is this:

到目前为止我的代码是这样的:

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

@Component({
  selector: 'myComponent',
  template: 
    `<h1>Returned Value {{returnedString}}</h1>,`, 
  inputs:['number']
})
export class MyComponent  { 
  myStringArray: string[]; 
  returnedString: string;

  constructor(){
    this.myStringArray = ['First','Second','Third','Forth','Fifth','Sixth'];
    this.returnedString = 'number'+this.myStringArray['number'.valueOf()];
  }
}

I am calling this component as follows

我调用这个组件如下

<myComponent [number]=1></myComponent>

I print the value returned to the screen and get 'undefined'.

我打印返回到屏幕的值并得到“未定义”。

Any ideas folks?

大家有什么想法吗?

回答by Evans M.

Since you want to bind to a custom property import Input and OnChanges from core and then implement as Input to create your custom property. The OnChanges just ensures your value gets updated when the bound value changes.

由于您想绑定到自定义属性,从核心导入 Input 和 OnChanges,然后实现为 Input 以创建您的自定义属性。OnChanges 只是确保您的值在绑定值更改时更新。

Remove the inputs key from your component decorator

从组件装饰器中删除输入键

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

@Component({
  selector: 'myComponent',
  template: 
    `<h1>Returned Value {{returnedString}}</h1>,`
})
export class MyComponent  implements OnChanges { 
  myStringArray: string[];
  returnedString: string;
  @Input() inputNumber: number; 

  constructor(){
    this.myStringArray = ['First','Second','Third','Forth','Fifth','Sixth'];
    this.returnedString = 'number'+this.myStringArray[Number(this.inputNumber)];
  }

  ngOnChanges() {
    this.returnedString = 'number'+this.myStringArray[Number(this.inputNumber)];   
  }
}

Update your code usage to the following

将您的代码用法更新为以下内容

<myComponent [inputNumber]="1"></myComponent>

Here is a sample plunker. https://plnkr.co/edit/S074zoVJ3ktQDKkcQgxe?p=preview

这是一个示例 plunker。 https://plnkr.co/edit/S074zoVJ3ktQDKkcQgxe?p=preview

回答by Som

I had tough time to send string inputs. here is the correct way,

我很难发送字符串输入。这是正确的方法,

<myComponent [stringvar]="'string value'"></myComponent>

"string value" will not work. angular expecting object or number inside double quotes. string should be inside single quotes within double quotes "'string'"

“字符串值”将不起作用。双引号内的角度期望对象或数字。字符串应该在双引号内的单引号内“'string'”

回答by tika

It's quite simple. See this demo.Let's say you have two components parentand child. And you want to pass a variable to childand modify it there, say views.

这很简单。看到这个演示。假设您有两个组件parentchild。你想传递一个变量child并在那里修改它,比如views.

On parenttemplate:

parent模板上:

<child [(views)]="views"></child>

<child [(views)]="views"></child>

On childcomponent:

child组件上:

  @Input() views: number;
  @Output() viewsChange = new EventEmitter<number>();

  // Bind this function to button click or some events:
  updateViews() {
    this.views++;
    this.viewsChange.emit(this.views); // Emit the value to parent:
  }


Detail explanation:When you bind [(views)]in parent, it is acting as:

详细说明:当你[(views)]在 parent 中绑定时,它的作用是:

<child 
        [views]="views" 
        (viewsChange)="views = $event">
</child>

So, it is listening to viewsChangeoutput function. Whenever, you do viewsChange.emit, the parent viewsget updated.

所以,它正在监听viewsChange输出功能。每当你这样做时viewsChange.emit,父级views都会更新。

Gotcha: The output function should be precisely named $var + "Change". If you chose to name something else you will have to do:

问题:输出函数应该精确地命名为$var + "Change"。如果您选择命名其他名称,则必须执行以下操作:

<child 
            [views]="views" 
            (customEmitterFunction)="views = $event">
    </child> 

回答by Ali Baig

You need to create a number variable in your component too that will hold the value.

您还需要在组件中创建一个数字变量来保存该值。

import {Component, OnInit} from '@angular/core';
@Component({
  selector: 'myComponent',
  template: 
    `<h1>Returned Value {{returnedString}}</h1>,`, 
  inputs:['myNum']
})
export class MyComponent implements OnInit { 
  myStringArray: string[] = ['First','Second','Third','Forth','Fifth','Sixth']; 
  returnedString: string;
  public myNum: number;  <= here is your variable

  ngOnInit() {
      //you can use this.myNum anywhere now like this
      this.returnedString = 'number '+ this.myStringArray[this.myNum];
  }

  constructor(){

  }
}

You may have to change the name of your input because number is a keyword.

您可能需要更改输入的名称,因为 number 是keyword.

Another Note: You have to use OnInitinstead of constructorto start using your inputs. ngOnInitis an Angular2 lifecyclemethod that is called by Angular when it's done building the component and evaluated the bindings

另一个注意事项:您必须使用OnInit而不是constructor开始使用您的输入。ngOnInitAngular2 lifecycleAngular 在完成构建组件并评估绑定时调用的方法

回答by AngularChef

Here is another alternative. It demonstrates how to use a getter for returnedString. Less code needed than with ngOnChanges.

这是另一种选择。它演示了如何使用 getter for returnedString。所需的代码比使用ngOnChanges.

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

@Component({
  selector: 'my-cmp',
  template: `
    <p>returnedString = {{ returnedString }}</p>
  `
})
export class MyComponent {
  myStringArray: string[]  = ['First','Second','Third','Forth','Fifth','Sixth'];
  @Input() stringIndex: number;

  get returnedString(): string {
    if (this.stringIndex !== undefined) {
      return this.myStringArray[this.stringIndex];
    }
  }
}

回答by arpho

In order to pass data from the child component to the father component you shuold set an Output parameter, to trigger the signal your component should implements the OnChanges interface, your component should be like this

为了将数据从子组件传递到父组件,您应该设置一个 Output 参数,以触发您的组件应该实现 OnChanges 接口的信号,您的组件应该是这样的

    import { Component, Input,Output,EventEmitter,OnChanges,SimpleChanges } from '@angular/core';

@Component({
  selector: 'my-cmp',
  template: `
    <p>returnedString = {{ returnedString }}</p>
  `
})
export class MyComponent implements OnChanges {
  myStringArray: string[]  = ['First','Second','Third','Forth','Fifth','Sixth'];
  @Input() stringIndex: number;
 @Output() cardinalNumber:EventEmitter<string> = new EventEmitter<string>();// you define an Output, this will emit a signal that will received from the father Component

  ngOnChanges(changes:SimpleChanges) {
  // when the input changes we emit a signal
  this.cardinalNumber.emit(this.myStringArray[this.stringIndex]);
  }
  get returnedString(): string {
    if (this.stringIndex !== undefined) {
      return this.myStringArray[this.stringIndex];
    }
  }
}

then in the template of the father component you should insert :

然后在父组件的模板中,您应该插入:

    <my-cmp [stringIndex]=the parameter in father Component's controller
         (cardinalNumber)="method2beinvoked($event)">
</my-cmp>

method2beInvoked is the method in the father component that handles the message; or you could do like this:

method2beInvoked 是父组件中处理消息的方法;或者你可以这样做:

    <my-cmp [stringIndex]=the parameter in father Component's controller
         (cardinalNumber)="parameter=$event")>
</my-cmp

where parameter is a parameter in the father's component controller

其中参数是父组件控制器中的参数