javascript 单击按钮时,Angular 将输入变量传递给另一个组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53127724/
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
Angular pass input variable to another component on button click
提问by Emac
I come from a Python background, but I started trying to learn Angular and I'm really having trouble. Working between components is confusing to me and I can't figure it out. I made a good example that I think if someone helped me with it would go along way towards understanding Angular.
我来自 Python 背景,但我开始尝试学习 Angular,但我真的遇到了麻烦。在组件之间工作让我感到困惑,我无法弄清楚。我做了一个很好的例子,我认为如果有人帮助我,它会朝着理解 Angular 的方向发展。
I just have two components: a "header" component and an app component. In the header component, I ask for the user's name and they click a button, and then it should show "Hello {{name}}" in the next component. I cannot get it to work to say the least and it's really frustrating. The Header part seems to work okay, but it's just not communicating with the other component at all. Neither the button part or the "name" part are working so I am clearly misunderstanding something I need to do when it comes to listening from the parent component.
我只有两个组件:一个“标题”组件和一个应用程序组件。在标题组件中,我询问用户的姓名,然后他们单击一个按钮,然后它应该在下一个组件中显示“Hello {{name}}”。至少可以说我无法让它工作,这真的很令人沮丧。Header 部分似乎工作正常,但它根本不与其他组件通信。按钮部分或“名称”部分都没有工作,所以我显然误解了在从父组件收听时我需要做的事情。
Here is my Header HTML:
这是我的标题 HTML:
Name: <input type="text" id="userInput" value="Joe">
<button (click)=showName()>Show More</button>
Here is my Header TS:
这是我的标题 TS:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
bodyDiv = false;
inputName = '';
@Output() buttonClicked = new EventEmitter();
constructor() { }
ngOnInit() {
}
showName() {
console.log('showName clicked.');
this.bodyDiv = true;
this.inputName = document.getElementById('userInput').value;
console.log(this.inputName);
console.log(this.bodyDiv);
this.buttonClicked.emit(this.bodyDiv);
this.buttonClicked.emit(this.inputName);
}
}
Here is the main Component's HTML:
这是主要组件的 HTML:
<app-header (buttonClicked)='showNextComponent($event)'></app-header>
<p *ngIf="![hiddenDiv]" [inputName]="name">Hello {{ name }} </p>
Here is the main component's TS:
这是主要组件的 TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
hiddenComponent = true;
title = 'show-button';
showNextComponent() {
console.log('Button clicked.');
this.hiddenComponent = false;
console.log(this.hiddenComponent);
}
}
So who can show me what I'm doing wrong and help figure out Angular a little better? :) Thank you!
那么谁能告诉我我做错了什么,并帮助我更好地了解 Angular 呢?:) 谢谢!
采纳答案by Ajay Ojha
replace showName function with below code :
用以下代码替换 showName 函数:
showName() {
console.log('showName clicked.');
this.bodyDiv = true;
this.inputName = document.getElementById('userInput').value;
console.log(this.inputName);
console.log(this.bodyDiv);
this.buttonClicked.emit(this.inputName);
}
name:string
showNextComponent(value:string) {
this.name = value;
}
replace below code in your html :
在您的 html 中替换以下代码:
<app-header (buttonClicked)='showNextComponent($event)'></app-header>
<p *ngIf="name">Hello {{ name }} </p>
Please let me if you have any question and I would suggest try to use ngmodel or something else instead of directly communicating with the DOM.
如果您有任何问题,请告诉我,我建议尝试使用 ngmodel 或其他东西,而不是直接与 DOM 通信。
回答by Rahul
There are couple of ways to communicate from one component to another in angular - Using @Input()in your child component will expects an input from parent component and @Output()from your child component will emit an event from the child component
有几种方法可以以角度从一个组件到另一个组件进行通信 -@Input()在您的子组件中使用将需要来自父组件的输入,而@Output()您的子组件将从子组件发出一个事件
So in your case if you want to pass a value from parent to child you need to use input property or decorator on your child property - I will provide you the code but just go through proper guidance from the link provided this will make you to create better angular applications https://angular.io/guide/component-interaction
因此,在您的情况下,如果您想将值从父级传递给子级,则需要在子级属性上使用输入属性或装饰器 - 我将为您提供代码,但只需从链接中获得适当的指导,前提是这将使您创建更好的角度应用程序https://angular.io/guide/component-interaction
First you need to swap your components your header component should be your parent and the child component will be your main component - if you want to work in the same way just move your codes vice versa
首先你需要交换你的组件,你的头组件应该是你的父组件,子组件将是你的主要组件 - 如果你想以同样的方式工作,反之亦然
Header html
标题html
Name: <input type="text" id="userInput" name='userInput' [(ngModel)]='inputName' value="Joe">
<button (click)=showName()>Show More</button>
<div [hidden]='bodyDiv'>
<app-header [bindName]='inputName'></app-header>
</div>
Header Component
标题组件
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
bodyDiv = true;
inputName = '';
constructor() { }
ngOnInit() {
}
showName() {
bodyDiv = false;
}
}
Main Component Html
主要组件 Html
<p>Hello {{ bindName }} </p>
Main component ts
主要成分 ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@Input()
bindName: string;
}
In your header component the inputNameproperty will be binded using two way data binding where i used [(ngModel)]='inputName'so whatever you enter in the input text it will be updated in your inputNameproperty
在您的标题组件中,inputName属性将使用我使用的两种方式数据绑定进行绑定,[(ngModel)]='inputName'因此无论您在输入文本中输入什么,它都会在您的inputName属性中更新
Now we need to do only one thing just to show your child component with any event - so when the button is clicked the div with [hidden]property will be false and it will be displayed and as we pass the inputNameto the child Component it will be updated
现在我们只需要做一件事就可以显示带有任何事件的子组件 - 因此,当单击按钮时,带有[hidden]属性的 div将为 false 并且它将被显示,并且当我们将 传递inputName给子组件时,它将被更新
And finally the child component will be displayed and the input written in the text will be updated in the child component - when the child component html displays the bindNamewill be updated and there will be result you expected
最后将显示子组件,并在子组件中更新写入文本的输入 - 当子组件 html 显示时,bindName将更新,并且会出现您期望的结果
That's all I think this should work well - Try this and let me know - Thanks Happy coding !!
这就是我认为这应该可以正常工作的全部内容 - 试试这个并让我知道 - 谢谢快乐编码!
Don't forget to look into the link above where you can see many types of component interactions
不要忘记查看上面的链接,在那里您可以看到多种类型的组件交互
回答by zer0
Here is a slightly modified and working sample: https://stackblitz.com/edit/angular-jhhctr
这是一个稍微修改和工作的示例:https: //stackblitz.com/edit/angular-jhhctr
The event emitter in the header component emits the name (string) which is the $eventin showNextComponent($event). You have to capture this in the main component and assign it to a local variable to be able to use it in the main component's template as {{name}}
header 组件中的事件发射器发出名称(字符串),它是$eventin showNextComponent($event)。您必须在主组件中捕获它并将其分配给一个局部变量才能在主组件的模板中使用它作为{{name}}
[inputName]="name"is incorrect. You can pass values like that to angular components not to actual HTML DOM elements.
[inputName]="name"是不正确的。您可以将这样的值传递给角度组件而不是实际的 HTML DOM 元素。

