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

新手上路,请多包涵

我来自 Python 背景,但我开始尝试学习 Angular,但我真的遇到了麻烦。在组件之间工作让我感到困惑,我无法弄清楚。我举了一个很好的例子,我认为如果有人帮助我,它会帮助我理解 Angular。

我只有两个组件:一个“header”组件和一个 app 组件。在标头组件中,我要求输入用户名,然后他们单击一个按钮,然后它应该在下一个组件中显示“Hello {{name}}”。至少可以说我无法让它工作,这真的很令人沮丧。 Header 部分似乎工作正常,但它根本不与其他组件通信。按钮部分或“名称”部分都不起作用,所以我显然误解了在从父组件监听时我需要做的事情。

这是我的标题 HTML:

 Name: <input type="text" id="userInput" value="Joe">

<button (click)=showName()>Show More</button>

这是我的标题 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);
  }
}

这是主要组件的 HTML:

 <app-header (buttonClicked)='showNextComponent($event)'></app-header>

<p *ngIf="![hiddenDiv]" [inputName]="name">Hello {{ name }} </p>

这是主要组件的 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);
  }
}

那么谁能告诉我我做错了什么并帮助我更好地理解 Angular 呢? :) 谢谢!

原文由 Emac 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 263
2 个回答

用以下代码替换 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;
  }

在您的 html 中替换以下代码:

 <app-header (buttonClicked)='showNextComponent($event)'></app-header>

<p *ngIf="name">Hello {{ name }} </p>

如果您有任何问题,请告诉我,我建议尝试使用 ngmodel 或其他东西,而不是直接与 DOM 通信。

原文由 Ajay Ojha 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是一个稍微修改过的工作示例: https ://stackblitz.com/edit/angular-jhhctr

标头组件中的事件发射器发出名称(字符串),即 $event 中的 --- showNextComponent($event) 。您必须在主要组件中捕获它并将其分配给局部变量才能在主要组件的模板中使用它作为 {{name}}

[inputName]="name" 不正确。您可以将这样的值传递给角度组件,而不是传递给实际的 HTML DOM 元素。

原文由 zer0 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题