javascript - 将一个组件的值传递给另一个 Angular
问题描述
我在组件中有一个输入元素,如下所示:
<input #inputDate
(blur)="realDate(inputDate.value); inputDate.value='' ">
然后我想在另一个组件上使用(显示)inputDate 的值,我该怎么做?我是 Angular 新手,任何帮助将不胜感激。
解决方案
如果要将组件发送到父组件,可以@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 发出值并让多个组件监听您输入的更改),您还可以考虑使用Services
which 可能有助于您在多个组件中重用其中的一些逻辑。Subject
推荐阅读
- database - 在 DB2 数据库中批量导入 1000 个 *.ixf 文件
- object - Edge没有显示PDF对象的下载选项?
- java - 错误“列表中的最大表达式数为 1000”的分区列表
- r - 将数据框保存到列表中的值
- c# - 如何从 Startup 中配置的容器解析类库中的依赖项?
- typescript - 如何在 Visual Studio 2017 中指定 tsconfig.json
- r - 在 .csv 中将字符串更改为整数
- java - gradle windows java.io.IOException: CreateProcess error=206, 文件名太长
- asp.net-mvc-4 - 使用 MM/YYYY 格式为 Bootstrap-datetimepicker 分配值显示不正确的年份
- c# - c# 中缺少来自 422 的响应正文