简体   繁体   English

单击按钮时将角度传递输入变量传递给另一个组件

[英]Angular pass input variable to another component on button click

I come from a Python background, but I started trying to learn Angular and I'm really having trouble. 我来自Python,但是我开始尝试学习Angular,但确实遇到了麻烦。 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. 我举了一个很好的例子,我认为如果有人帮助我,它将有助于理解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. 在标题组件中,我要求输入用户名,然后他们单击一个按钮,然后在下一个组件中应显示“ Hello {{name}}”。 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. Header部分似乎可以正常工作,但根本不与其他组件进行通信。 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. 按钮部分或“名称”部分都不起作用,因此当涉及到从父组件进行侦听时,我显然误解了我需要做的事情。

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? 那么,谁能告诉我我在做错什么,并帮助我更好地了解Angular? :) Thank you! :) 谢谢!

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); } 
replace below code in your main component. 在您的主要组件中替换以下代码。

 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通信。

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 $event in showNextComponent($event) . 在头部件的事件发射器发射其是名称(字符串) $eventshowNextComponent($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}} 您必须在主要组件中捕获它,并将其分配给本地变量,然后才能在主要组件的模板中以{{name}}使用它

[inputName]="name" is incorrect. [inputName]="name"不正确。 You can pass values like that to angular components not to actual HTML DOM elements. 您可以将这样的值传递给角度组件,而不传递给实际的HTML DOM元素。

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 主要成分

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 inputName property 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 inputName property 在标题组件中, 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 inputName to 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 bindName will 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 不要忘了查看上面的链接,在这里您可以看到许多类型的组件交互

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM