首页 > 解决方案 > 将一个组件的值传递给另一个 Angular

问题描述

我在组件中有一个输入元素,如下所示:

   <input #inputDate
          (blur)="realDate(inputDate.value); inputDate.value='' ">

然后我想在另一个组件上使用(显示)inputDate 的值,我该怎么做?我是 Angular 新手,任何帮助将不胜感激。

标签: javascriptcssangularhtmltypescript

解决方案


如果要将组件发送到父组件,可以@Output()一起使用装饰器和事件发射器,通过执行以下操作将值发送到父组件:

@Output()
public input: EventEmitter<string> = new EventEmitter<string>();

<my-input (input)="onInputChange()"></my-input>

// Method to detect for changes on #myInput
public onMyInputChanges(): void {
    // ...
    input.emit(<#myInputValue>);
}

我将把它作为练习留给你,让你弄清楚如何检测上面输入元素的变化。

如果你想将你的值发送给子组件,你可以使用@Input()装饰器并像这样传递它:

<input #myInput [(ngModel)]="inputValue">

public inputValue: string = '';

<child-component [value]="inputValue"></child-component>

因为您想直接使用 HTML 中的值,请考虑使用@ViewChild装饰器,它允许您使用本地引用#inputDate来获取值,如下所示:

@ViewChild('inputDate')
public myInput: HTMLInputElement;

然后您可以通过访问您的值myInput.value并在您的组件上使用它或使用上述方法传递它。

如果这是您的用例(例如,从 a 发出值并让多个组件监听您输入的更改),您还可以考虑使用Serviceswhich 可能有助于您在多个组件中重用其中的一些逻辑。Subject


推荐阅读