【问题标题】:Angular 2 Forms . Passing data from one component to another with a text box on clicking of a button角 2 形式。单击按钮时使用文本框将数据从一个组件传递到另一个组件
【发布时间】:2017-06-22 17:05:50
【问题描述】:

我是 angular 2 的初学者。我希望在文本框中输入数据,在输入时(比如单击输入按钮),我需要将数据带到另一个组件,在其中我可以将数据附加到另一个变量。我该怎么做呢 ?提前致谢。

【问题讨论】:

  • 通过另一个组件您要在路由期间共享或父级的另一个子组件

标签: angular angular2-routing angular2-forms


【解决方案1】:

通常你应该有嵌套组件,比如说一个子组件,它在按下 Enter-Button 时向父组件触发一个事件。使用 ()-Binding,您可以在父组件中注册该事件并读取使用参数给出的值。

<form>
 // your form...
    <button type="submit" (click)="clickButton();>Submit</button>
</form>

在你的 ts 中:

export class ChildComponent {
    @Output() buttonWasClicked = new EventEmitter<string>();

    public clickButton = (): void => {
        this.buttonWasClicked.emit(this.myValueToPass);
    }
}

在您的父组件中,您正在使用这样的子组件:

<child-component (buttonWasClicked)="makeSomething($event)"></child-component>

export class ParentComponent {

    public makeSomething(valueWhichWasPassed: string) {
        // Make Something with value
    }
}

这是我在这里输入的伪代码。

【讨论】:

    【解决方案2】:

    尝试使用App.component,

    App.component

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `<h2> Hello </h2>`,
    })
    
    export class AppComponent {
      @Input() textBoxValue: string = ''
    }

    在组件 1 中编写以下代码

    import { Component } from '@angular/core';
    import { AppComponent } from './appComponent'
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <input type="text" [(ngModal)]="textboxValue"/>
          <button type="button" (click)="onEntered()"> Enter   </button>
        </div>
      `
    })
    export class Component1{
      textboxValue: string = '';
    
      constructor(private appComponent:AppComponent){
    
      }
    
      onEntered(): void{
        this.appComponent.textBoxValue = this.textboxValue;
      }
    
    }

    在组件 2 中从 AppComponent 中获取值

    value: string = this.appComponent.textBoxValue;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2023-01-21
      • 2019-08-03
      • 2019-04-07
      • 2019-12-16
      相关资源
      最近更新 更多