将一个组件的值传递给另一个Angular

时间:2019-02-05 14:38:01

标签: javascript css angular html5 typescript

我在类似这样的组件中有一个输入元素:

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

然后我想在另一个组件上使用(显示)inputDate的值,我该怎么做? 我对angular并不陌生,将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果要将其发送到父组件,请将其绑定到ngModel并使用事件发射器发送该值。

如果要将其发送到子组件,请使用@Input装饰器。 (parent-to-child

但是,要从html发送值时,可以使用jquery或document.querySelector来获取值

This可能会帮助您

答案 1 :(得分:0)

如果要将组件发送到父组件,则可以使用@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访问您的值,并在您的组件上使用它,或者将其传递给上述方法。

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

相关问题